


'''simple docstring'''

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   __lowerCAmelCase						(lowercase_					):





      '''simple docstring'''






      def 				UpperCamelCase__		(self   :   Any			):

             '''simple docstring'''







             lowercase__				      =			self.config_class(**self.inputs_dict			)
             self.parent.assertTrue(hasattr(UpperCamelCase       ,						'''hidden_sizes'''			)			)
             self.parent.assertTrue(hasattr(UpperCamelCase       ,						'''num_encoder_blocks'''			)			)






class   __lowerCAmelCase						:





      '''simple docstring'''






      def __init__(self   :   str       ,						UpperCamelCase   :   Tuple       ,						UpperCamelCase   :   str=13       ,						UpperCamelCase   :   Optional[Any]=64       ,						UpperCamelCase   :   Optional[int]=3       ,						UpperCamelCase   :   Union[str, Any]=4       ,						UpperCamelCase   :   List[Any]=[2, 2, 2, 2]       ,						UpperCamelCase   :   int=[8, 4, 2, 1]       ,						UpperCamelCase   :   Any=[16, 32, 64, 128]       ,						UpperCamelCase   :   Optional[Any]=[1, 4, 8, 16]       ,						UpperCamelCase   :   Dict=False       ,						UpperCamelCase   :   Optional[Any]=True       ,						UpperCamelCase   :   Any="gelu"       ,						UpperCamelCase   :   Optional[int]=0.1       ,						UpperCamelCase   :   Tuple=0.02       ,						UpperCamelCase   :   Tuple=3       ,						UpperCamelCase   :   Tuple=None       ,						):

             '''simple docstring'''







             lowercase__				      =			parent
             lowercase__				      =			batch_size
             lowercase__				      =			image_size
             lowercase__				      =			num_channels
             lowercase__				      =			num_encoder_blocks
             lowercase__				      =			sr_ratios
             lowercase__				      =			depths
             lowercase__				      =			hidden_sizes
             lowercase__				      =			downsampling_rates
             lowercase__				      =			is_training
             lowercase__				      =			use_labels
             lowercase__				      =			hidden_act
             lowercase__				      =			hidden_dropout_prob
             lowercase__				      =			initializer_range
             lowercase__				      =			num_labels
             lowercase__				      =			scope



      def 				UpperCamelCase__		(self   :   Optional[Any]			):

             '''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.image_size, self.image_size]       ,						self.num_labels			)

             lowercase__				      =			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 				UpperCamelCase__		(self   :   Optional[int]       ,						UpperCamelCase   :   Optional[Any]       ,						UpperCamelCase   :   Any       ,						UpperCamelCase   :   Optional[int]			):

             '''simple docstring'''







             lowercase__				      =			PoolFormerModel(config=UpperCamelCase			)
             model.to(UpperCamelCase			)
             model.eval()
             lowercase__				      =			model(UpperCamelCase			)
             lowercase__				      =			lowercase__				      =			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 				UpperCamelCase__		(self   :   Dict			):

             '''simple docstring'''







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






@require_torch
class   __lowerCAmelCase						(lowercase_  ,					lowercase_  ,					unittest.TestCase					):





      '''simple docstring'''






      lowerCAmelCase__ :					Any   =							(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
      lowerCAmelCase__ :					Union[str, Any]   =							(
          {"""feature-extraction""": PoolFormerModel, """image-classification""": PoolFormerForImageClassification}
          if is_torch_available()
          else {}
      )

      lowerCAmelCase__ :					Tuple   =							False
      lowerCAmelCase__ :					Tuple   =							False
      lowerCAmelCase__ :					str   =							False
      lowerCAmelCase__ :					Tuple   =							False
      lowerCAmelCase__ :					int   =							False



      def 				UpperCamelCase__		(self   :   List[Any]			):

             '''simple docstring'''







             lowercase__				      =			PoolFormerModelTester(self			)
             lowercase__				      =			PoolFormerConfigTester(self       ,						config_class=UpperCamelCase			)



      def 				UpperCamelCase__		(self   :   Union[str, Any]			):

             '''simple docstring'''







             self.config_tester.run_common_tests()



      def 				UpperCamelCase__		(self   :   str			):

             '''simple docstring'''







             lowercase__				      =			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*UpperCamelCase			)



      @unittest.skip('''PoolFormer does not use inputs_embeds'''			)
      def 				UpperCamelCase__		(self   :   Any			):

             '''simple docstring'''







             pass



      @unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'''			)
      def 				UpperCamelCase__		(self   :   Union[str, Any]			):

             '''simple docstring'''







             pass



      def 				UpperCamelCase__		(self   :   List[str]			):

             '''simple docstring'''







             def check_hidden_states_output(UpperCamelCase   :   str       ,						UpperCamelCase   :   Tuple       ,						UpperCamelCase   :   List[str]			):
                    lowercase__				      =			model_class(UpperCamelCase			)
                    model.to(UpperCamelCase			)
                    model.eval()

                    with torch.no_grad():
                           lowercase__				      =			model(**self._prepare_for_class(UpperCamelCase       ,						UpperCamelCase			)			)

                    lowercase__				      =			outputs.hidden_states

                    lowercase__				      =			self.model_tester.num_encoder_blocks
                    self.assertEqual(len(UpperCamelCase			)       ,						UpperCamelCase			)

                    # 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,
                        ]       ,						)

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

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

                    check_hidden_states_output(UpperCamelCase       ,						UpperCamelCase       ,						UpperCamelCase			)



      def 				UpperCamelCase__		(self   :   int			):

             '''simple docstring'''







             if not self.model_tester.is_training:
                    return

             lowercase__      ,lowercase__				      =			self.model_tester.prepare_config_and_inputs_for_common()
             lowercase__				      =			True

             for model_class in self.all_model_classes:
                    if model_class in get_values(UpperCamelCase			):
                           continue
                    lowercase__				      =			model_class(UpperCamelCase			)
                    model.to(UpperCamelCase			)
                    model.train()
                    lowercase__				      =			self._prepare_for_class(UpperCamelCase       ,						UpperCamelCase       ,						return_labels=UpperCamelCase			)
                    lowercase__				      =			model(**UpperCamelCase			).loss
                    loss.backward()



      def 				UpperCamelCase__		(self   :   Optional[Any]			):

             '''simple docstring'''







             lowercase__      ,lowercase__				      =			self.model_tester.prepare_config_and_inputs_for_common()

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

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






      @slow
      def 				UpperCamelCase__		(self   :   Any			):

             '''simple docstring'''







             for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__				      =			PoolFormerModel.from_pretrained(UpperCamelCase			)
                    self.assertIsNotNone(UpperCamelCase			)






def _SCREAMING_SNAKE_CASE				()	->	Any:






       """simple docstring"""







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

@require_torch
class   __lowerCAmelCase						(unittest.TestCase					):





      '''simple docstring'''






      @slow
      def 				UpperCamelCase__		(self   :   List[str]			):

             '''simple docstring'''







             lowercase__				      =			PoolFormerImageProcessor()
             lowercase__				      =			PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''			).to(UpperCamelCase			)

             lowercase__				      =			image_processor(images=prepare_img()       ,						return_tensors='''pt'''			).to(UpperCamelCase			)

             # forward pass
             with torch.no_grad():
                    lowercase__				      =			model(**UpperCamelCase			)

             # verify the logits
             lowercase__				      =			torch.Size((1, 1000)			)
             self.assertEqual(outputs.logits.shape       ,						UpperCamelCase			)

             lowercase__				      =			torch.tensor([-0.61_13, 0.16_85, -0.04_92]			).to(UpperCamelCase			)
             self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,						UpperCamelCase       ,						atol=1E-4			)			)








'''simple docstring'''

import math
import os

import cva
import numpy as np

lowerCamelCase							:       Optional[Any]  						=     2_5_5.0

def _SCREAMING_SNAKE_CASE				(A  ,			A	)	->	float:






       """simple docstring"""







       lowercase__				      =			np.mean((original - contrast) ** 2	)
       if mse == 0:
              return 100

       return 20 * math.logaa(PIXEL_MAX / math.sqrt(A	)	)

def _SCREAMING_SNAKE_CASE				()	->	None:






       """simple docstring"""







       lowercase__				      =			os.path.dirname(os.path.realpath(A	)	)
       # Loading images (original image and compressed image)
       lowercase__				      =			cva.imread(os.path.join(A  ,			'''image_data/original_image.png'''	)	)
       lowercase__				      =			cva.imread(os.path.join(A  ,			'''image_data/compressed_image.png'''	)  ,			1	)

       lowercase__				      =			cva.imread(os.path.join(A  ,			'''image_data/PSNR-example-base.png'''	)	)
       lowercase__				      =			cva.imread(
           os.path.join(A  ,			'''image_data/PSNR-example-comp-10.jpg'''	)  ,			1	)

       # Value expected: 29.73dB
       print('''-- First Test --'''	)
       print(f"PSNR value is {peak_signal_to_noise_ratio(A  ,			A	)} dB"	)

       # # Value expected: 31.53dB (Wikipedia Example)
       print('''\n-- Second Test --'''	)
       print(f"PSNR value is {peak_signal_to_noise_ratio(A  ,			A	)} dB"	)


if __name__ == "__main__":
 main()




