



import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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 MODEL_MAPPING, PoolFormerConfig, PoolFormerForImageClassification, PoolFormerModel
   from transformers.models.poolformer.modeling_poolformer import POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import PoolFormerImageProcessor


class 	snake_case_			(lowercase__	):




       """simple docstring"""






       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Union[str, Any]					   =		self.config_class(**self.inputs_dict)
             self.parent.assertTrue(hasattr(lowercase  ,"hidden_sizes"))
             self.parent.assertTrue(hasattr(lowercase  ,"num_encoder_blocks"))


class 	snake_case_			:




       """simple docstring"""






       def __init__(  self  ,lowercase  ,lowercase=13  ,lowercase=64  ,lowercase=3  ,lowercase=4  ,lowercase=[2, 2, 2, 2]  ,lowercase=[8, 4, 2, 1]  ,lowercase=[16, 32, 64, 128]  ,lowercase=[1, 4, 8, 16]  ,lowercase=False  ,lowercase=True  ,lowercase="gelu"  ,lowercase=0.1  ,lowercase=0.02  ,lowercase=3  ,lowercase=None  ,):

             """simple docstring"""





             UpperCAmelCase_	:						int					   =		parent
             UpperCAmelCase_	:						Dict					   =		batch_size
             UpperCAmelCase_	:						Any					   =		image_size
             UpperCAmelCase_	:						Any					   =		num_channels
             UpperCAmelCase_	:						Any					   =		num_encoder_blocks
             UpperCAmelCase_	:						Optional[Any]					   =		sr_ratios
             UpperCAmelCase_	:						Tuple					   =		depths
             UpperCAmelCase_	:						Tuple					   =		hidden_sizes
             UpperCAmelCase_	:						Optional[Any]					   =		downsampling_rates
             UpperCAmelCase_	:						List[Any]					   =		is_training
             UpperCAmelCase_	:						Any					   =		use_labels
             UpperCAmelCase_	:						List[str]					   =		hidden_act
             UpperCAmelCase_	:						Union[str, Any]					   =		hidden_dropout_prob
             UpperCAmelCase_	:						Dict					   =		initializer_range
             UpperCAmelCase_	:						Union[str, Any]					   =		num_labels
             UpperCAmelCase_	:						List[str]					   =		scope



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Any					   =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

             UpperCAmelCase_	:						int					   =		None
             if self.use_labels:
                   UpperCAmelCase_	:						List[str]					   =		ids_tensor([self.batch_size, self.image_size, self.image_size]  ,self.num_labels)

             UpperCAmelCase_	:						Tuple					   =		PoolFormerConfig(
                 image_size=self.image_size  ,num_channels=self.num_channels  ,num_encoder_blocks=self.num_encoder_blocks  ,depths=self.depths  ,hidden_sizes=self.hidden_sizes  ,hidden_act=self.hidden_act  ,hidden_dropout_prob=self.hidden_dropout_prob  ,initializer_range=self.initializer_range  ,)

             return config, pixel_values, labels



       def 			A_ (  self  ,lowercase  ,lowercase  ,lowercase):

             """simple docstring"""





             UpperCAmelCase_	:						Any					   =		PoolFormerModel(config=lowercase)
             model.to(lowercase)
             model.eval()
             UpperCAmelCase_	:						Any					   =		model(lowercase)
             UpperCAmelCase_	:						str					   =		self.image_size // 32.0
             self.parent.assertEqual(
                 result.last_hidden_state.shape  ,(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width))



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						List[Any]					   =		self.prepare_config_and_inputs()
             UpperCAmelCase_   ,   UpperCAmelCase_   ,   UpperCAmelCase_	:						Dict					   =		config_and_inputs
             UpperCAmelCase_	:						List[str]					   =		{"pixel_values": pixel_values}
             return config, inputs_dict


@require_torch
class 	snake_case_			(lowercase__			,			lowercase__			,			unittest.TestCase	):




       """simple docstring"""






       _lowerCamelCase           =					(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
       _lowerCamelCase           =					(
           {"""feature-extraction""": PoolFormerModel, """image-classification""": PoolFormerForImageClassification}
           if is_torch_available()
           else {}
       )

       _lowerCamelCase           =					False
       _lowerCamelCase           =					False
       _lowerCamelCase           =					False
       _lowerCamelCase           =					False
       _lowerCamelCase           =					False



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						int					   =		PoolFormerModelTester(self)
             UpperCAmelCase_	:						int					   =		PoolFormerConfigTester(self  ,config_class=lowercase)



       def 			A_ (  self):

             """simple docstring"""





             self.config_tester.run_common_tests()



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						int					   =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase)



       @unittest.skip("PoolFormer does not use inputs_embeds")
       def 			A_ (  self):

             """simple docstring"""





             pass



       @unittest.skip("PoolFormer does not have get_input_embeddings method and get_output_embeddings methods")
       def 			A_ (  self):

             """simple docstring"""





             pass



       def 			A_ (  self):

             """simple docstring"""





             def check_hidden_states_output(lowercase  ,lowercase  ,lowercase):
                   UpperCAmelCase_	:						List[Any]					   =		model_class(lowercase)
                   model.to(lowercase)
                   model.eval()

                   with torch.no_grad():
                         UpperCAmelCase_	:						Dict					   =		model(**self._prepare_for_class(lowercase  ,lowercase))

                   UpperCAmelCase_	:						Tuple					   =		outputs.hidden_states

                   UpperCAmelCase_	:						Optional[int]					   =		self.model_tester.num_encoder_blocks
                   self.assertEqual(len(lowercase)  ,lowercase)

                   # verify the first hidden states (first block)
                   self.assertListEqual(
                       list(hidden_states[0].shape[-3:])  ,[
                           self.model_tester.hidden_sizes[0],
                           self.model_tester.image_size // 4,
                           self.model_tester.image_size // 4,
                       ]  ,)

             UpperCAmelCase_   ,   UpperCAmelCase_	:						List[str]					   =		self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_	:						Dict					   =		True
                   check_hidden_states_output(lowercase  ,lowercase  ,lowercase)

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   UpperCAmelCase_	:						Optional[int]					   =		True

                   check_hidden_states_output(lowercase  ,lowercase  ,lowercase)



       def 			A_ (  self):

             """simple docstring"""





             if not self.model_tester.is_training:
                   return

             UpperCAmelCase_   ,   UpperCAmelCase_	:						int					   =		self.model_tester.prepare_config_and_inputs_for_common()
             UpperCAmelCase_	:						List[Any]					   =		True

             for model_class in self.all_model_classes:
                   if model_class in get_values(lowercase):
                         continue
                   UpperCAmelCase_	:						Optional[int]					   =		model_class(lowercase)
                   model.to(lowercase)
                   model.train()
                   UpperCAmelCase_	:						Tuple					   =		self._prepare_for_class(lowercase  ,lowercase  ,return_labels=lowercase)
                   UpperCAmelCase_	:						Union[str, Any]					   =		model(**lowercase).loss
                   loss.backward()



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_   ,   UpperCAmelCase_	:						Tuple					   =		self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_	:						Optional[Any]					   =		model_class(lowercase)
                   UpperCAmelCase_	:						Dict					   =		inspect.signature(model.forward)
                   # signature.parameters is an OrderedDict => so arg_names order is deterministic
                   UpperCAmelCase_	:						Optional[Any]					   =		[*signature.parameters.keys()]

                   UpperCAmelCase_	:						Optional[Any]					   =		["pixel_values"]
                   self.assertListEqual(arg_names[:1]  ,lowercase)



       @slow
       def 			A_ (  self):

             """simple docstring"""





             for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   UpperCAmelCase_	:						Any					   =		PoolFormerModel.from_pretrained(lowercase)
                   self.assertIsNotNone(lowercase)







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






      '''simple docstring'''







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





@require_torch
class 	snake_case_			(unittest.TestCase	):




       """simple docstring"""






       @slow
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Union[str, Any]					   =		PoolFormerImageProcessor()
             UpperCAmelCase_	:						Optional[Any]					   =		PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12").to(lowercase)

             UpperCAmelCase_	:						Any					   =		image_processor(images=prepare_img()  ,return_tensors="pt").to(lowercase)

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_	:						str					   =		model(**lowercase)

             # verify the logits
             UpperCAmelCase_	:						str					   =		torch.Size((1, 1000))
             self.assertEqual(outputs.logits.shape  ,lowercase)

             UpperCAmelCase_	:						int					   =		torch.tensor([-0.6113, 0.1685, -0.0492]).to(lowercase)
             self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,lowercase  ,atol=1E-4))





def  _snake_case			(							__snake_case       ,	__snake_case       ,	__snake_case     )  ->  list[int]:






      '''simple docstring'''







      if hue < 0 or hue > 3_6_0:
            raise Exception("hue should be between 0 and 360"     )

      if saturation < 0 or saturation > 1:
            raise Exception("saturation should be between 0 and 1"     )

      if value < 0 or value > 1:
            raise Exception("value should be between 0 and 1"     )

      UpperCAmelCase_	:						Tuple					   =		value * saturation
      UpperCAmelCase_	:						Union[str, Any]					   =		hue / 6_0
      UpperCAmelCase_	:						Tuple					   =		chroma * (1 - abs(hue_section % 2 - 1     ))
      UpperCAmelCase_	:						Tuple					   =		value - chroma

      if hue_section >= 0 and hue_section <= 1:
            UpperCAmelCase_	:						List[str]					   =		round(2_5_5 * (chroma + match_value)     )
            UpperCAmelCase_	:						str					   =		round(2_5_5 * (second_largest_component + match_value)     )
            UpperCAmelCase_	:						int					   =		round(2_5_5 * (match_value)     )
      elif hue_section > 1 and hue_section <= 2:
            UpperCAmelCase_	:						Union[str, Any]					   =		round(2_5_5 * (second_largest_component + match_value)     )
            UpperCAmelCase_	:						Union[str, Any]					   =		round(2_5_5 * (chroma + match_value)     )
            UpperCAmelCase_	:						int					   =		round(2_5_5 * (match_value)     )
      elif hue_section > 2 and hue_section <= 3:
            UpperCAmelCase_	:						List[str]					   =		round(2_5_5 * (match_value)     )
            UpperCAmelCase_	:						Any					   =		round(2_5_5 * (chroma + match_value)     )
            UpperCAmelCase_	:						Optional[int]					   =		round(2_5_5 * (second_largest_component + match_value)     )
      elif hue_section > 3 and hue_section <= 4:
            UpperCAmelCase_	:						str					   =		round(2_5_5 * (match_value)     )
            UpperCAmelCase_	:						Dict					   =		round(2_5_5 * (second_largest_component + match_value)     )
            UpperCAmelCase_	:						Optional[Any]					   =		round(2_5_5 * (chroma + match_value)     )
      elif hue_section > 4 and hue_section <= 5:
            UpperCAmelCase_	:						str					   =		round(2_5_5 * (second_largest_component + match_value)     )
            UpperCAmelCase_	:						Any					   =		round(2_5_5 * (match_value)     )
            UpperCAmelCase_	:						str					   =		round(2_5_5 * (chroma + match_value)     )
      else:
            UpperCAmelCase_	:						Optional[int]					   =		round(2_5_5 * (chroma + match_value)     )
            UpperCAmelCase_	:						Dict					   =		round(2_5_5 * (match_value)     )
            UpperCAmelCase_	:						Optional[int]					   =		round(2_5_5 * (second_largest_component + match_value)     )

      return [red, green, blue]







def  _snake_case			(							__snake_case       ,	__snake_case       ,	__snake_case     )  ->  list[float]:






      '''simple docstring'''







      if red < 0 or red > 2_5_5:
            raise Exception("red should be between 0 and 255"     )

      if green < 0 or green > 2_5_5:
            raise Exception("green should be between 0 and 255"     )

      if blue < 0 or blue > 2_5_5:
            raise Exception("blue should be between 0 and 255"     )

      UpperCAmelCase_	:						str					   =		red / 2_5_5
      UpperCAmelCase_	:						Dict					   =		green / 2_5_5
      UpperCAmelCase_	:						int					   =		blue / 2_5_5
      UpperCAmelCase_	:						Any					   =		max(__snake_case       ,	__snake_case       ,	__snake_case     )
      UpperCAmelCase_	:						Union[str, Any]					   =		value - min(__snake_case       ,	__snake_case       ,	__snake_case     )
      UpperCAmelCase_	:						Optional[Any]					   =		0 if value == 0 else chroma / value

      if chroma == 0:
            UpperCAmelCase_	:						Tuple					   =		0.0
      elif value == float_red:
            UpperCAmelCase_	:						List[str]					   =		6_0 * (0 + (float_green - float_blue) / chroma)
      elif value == float_green:
            UpperCAmelCase_	:						Union[str, Any]					   =		6_0 * (2 + (float_blue - float_red) / chroma)
      else:
            UpperCAmelCase_	:						Dict					   =		6_0 * (4 + (float_red - float_green) / chroma)

      UpperCAmelCase_	:						int					   =		(hue + 3_6_0) % 3_6_0

      return [hue, saturation, value]







def  _snake_case			(							__snake_case       ,	__snake_case     )  ->  bool:






      '''simple docstring'''







      UpperCAmelCase_	:						List[str]					   =		abs(hsv_a[0] - hsv_a[0]     ) < 0.2
      UpperCAmelCase_	:						Optional[Any]					   =		abs(hsv_a[1] - hsv_a[1]     ) < 0.002
      UpperCAmelCase_	:						Tuple					   =		abs(hsv_a[2] - hsv_a[2]     ) < 0.002

      return check_hue and check_saturation and check_value
