'''simple docstring'''

import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 EfficientNetForImageClassification, EfficientNetModel
      from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor




class    lowerCamelCase__  :



   def __init__(    self					,      lowerCAmelCase__					,      lowerCAmelCase__=13					,      lowerCAmelCase__=32					,      lowerCAmelCase__=3					,      lowerCAmelCase__=[3, 3, 5]					,      lowerCAmelCase__=[32, 16, 24]					,      lowerCAmelCase__=[16, 24, 40]					,      lowerCAmelCase__=[1, 1, 2]					,      lowerCAmelCase__=[1, 1, 2]					,      lowerCAmelCase__=[1, 6, 6]					,      lowerCAmelCase__=True					,      lowerCAmelCase__=True					,      lowerCAmelCase__=37					,      lowerCAmelCase__="gelu"					,      lowerCAmelCase__=10					,      )				->     Union[str, Any]:
        """simple docstring"""





        _UpperCamelCase  :str       =parent
        _UpperCamelCase  :str       =batch_size
        _UpperCamelCase  :Any       =image_size
        _UpperCamelCase  :str       =num_channels
        _UpperCamelCase  :Dict       =kernel_sizes
        _UpperCamelCase  :List[str]       =in_channels
        _UpperCamelCase  :List[str]       =out_channels
        _UpperCamelCase  :Any       =strides
        _UpperCamelCase  :Tuple       =num_block_repeats
        _UpperCamelCase  :Tuple       =expand_ratios
        _UpperCamelCase  :int       =is_training
        _UpperCamelCase  :Union[str, Any]       =hidden_act
        _UpperCamelCase  :Optional[Any]       =num_labels
        _UpperCamelCase  :Dict       =use_labels



   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        _UpperCamelCase  :Optional[int]       =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

        _UpperCamelCase  :List[Any]       =None
        if self.use_labels:
             _UpperCamelCase  :int       =ids_tensor([self.batch_size]					,      self.num_labels     )

        _UpperCamelCase  :int       =self.get_config()
        return config, pixel_values, labels



   def  _UpperCamelCase		(    self     )				->     Any:
        """simple docstring"""





        return EfficientNetConfig(
            num_channels=self.num_channels					,      kernel_sizes=self.kernel_sizes					,      in_channels=self.in_channels					,      out_channels=self.out_channels					,      strides=self.strides					,      num_block_repeats=self.num_block_repeats					,      expand_ratios=self.expand_ratios					,      hidden_act=self.hidden_act					,      num_labels=self.num_labels					,      )



   def  _UpperCamelCase		(    self					,      lowerCAmelCase__					,      lowerCAmelCase__					,      lowerCAmelCase__     )				->     int:
        """simple docstring"""





        _UpperCamelCase  :Dict       =EfficientNetModel(config=lowerCAmelCase__     )
        model.to(lowerCAmelCase__     )
        model.eval()
        _UpperCamelCase  :Optional[Any]       =model(lowerCAmelCase__     )
        # expected last hidden states: B, C, H // 4, W // 4
        self.parent.assertEqual(
            result.last_hidden_state.shape					,      (self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)					,      )



   def  _UpperCamelCase		(    self					,      lowerCAmelCase__					,      lowerCAmelCase__					,      lowerCAmelCase__     )				->     Any:
        """simple docstring"""





        _UpperCamelCase  :Any       =EfficientNetForImageClassification(lowerCAmelCase__     )
        model.to(lowerCAmelCase__     )
        model.eval()
        _UpperCamelCase  :Dict       =model(lowerCAmelCase__					,      labels=lowerCAmelCase__     )
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_labels)     )




   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        _UpperCamelCase  :Optional[Any]       =self.prepare_config_and_inputs()
        _UpperCamelCase       ,      _UpperCamelCase       ,      _UpperCamelCase  :Tuple       =config_and_inputs
        _UpperCamelCase  :Any       ={"""pixel_values""": pixel_values}
        return config, inputs_dict




@require_torch
class    lowerCamelCase__  (   __snake_case       ,				__snake_case       ,				unittest.TestCase     ):
   __UpperCAmelCase           =						(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
   __UpperCAmelCase           =						(
       {"""feature-extraction""": EfficientNetModel, """image-classification""": EfficientNetForImageClassification}
       if is_torch_available()
       else {}
   )

   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False



   def  _UpperCamelCase		(    self     )				->     Union[str, Any]:
        """simple docstring"""





        _UpperCamelCase  :Tuple       =EfficientNetModelTester(self     )
        _UpperCamelCase  :Dict       =ConfigTester(
            self					,      config_class=lowerCAmelCase__					,      has_text_modality=lowerCAmelCase__					,      hidden_size=37     )



   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()



   def  _UpperCamelCase		(    self     )				->     Tuple:
        """simple docstring"""





        return



   @unittest.skip(reason="""EfficientNet does not use inputs_embeds"""     )
   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        pass



   @unittest.skip(reason="""EfficientNet does not support input and output embeddings"""     )
   def  _UpperCamelCase		(    self     )				->     str:
        """simple docstring"""





        pass



   @unittest.skip(reason="""EfficientNet does not use feedforward chunking"""     )
   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        pass



   def  _UpperCamelCase		(    self     )				->     Dict:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :int       =self.model_tester.prepare_config_and_inputs_for_common()

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

             _UpperCamelCase  :Union[str, Any]       =["""pixel_values"""]
             self.assertListEqual(arg_names[:1]					,      lowerCAmelCase__     )



   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        _UpperCamelCase  :int       =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase__     )



   def  _UpperCamelCase		(    self     )				->     Tuple:
        """simple docstring"""





        def check_hidden_states_output(lowerCAmelCase__					,      lowerCAmelCase__					,      lowerCAmelCase__     ):
             _UpperCamelCase  :Any       =model_class(lowerCAmelCase__     )
             model.to(lowerCAmelCase__     )
             model.eval()

             with torch.no_grad():
                  _UpperCamelCase  :str       =model(**self._prepare_for_class(lowerCAmelCase__					,      lowerCAmelCase__     )     )

             _UpperCamelCase  :Optional[Any]       =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
             _UpperCamelCase  :Any       =sum(config.num_block_repeats     ) * 4
             self.assertEqual(len(lowerCAmelCase__     )					,      lowerCAmelCase__     )

             # EfficientNet'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 // 2, self.model_tester.image_size // 2]					,      )

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

        for model_class in self.all_model_classes:
             _UpperCamelCase  :Any       =True
             check_hidden_states_output(lowerCAmelCase__					,      lowerCAmelCase__					,      lowerCAmelCase__     )

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

             check_hidden_states_output(lowerCAmelCase__					,      lowerCAmelCase__					,      lowerCAmelCase__     )



   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        _UpperCamelCase  :List[str]       =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__     )



   @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""     )
   def  _UpperCamelCase		(    self     )				->     Tuple:
        """simple docstring"""





        pass



   @slow
   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _UpperCamelCase  :Tuple       =EfficientNetModel.from_pretrained(lowerCAmelCase__     )
             self.assertIsNotNone(lowerCAmelCase__     )




   @is_pipeline_test
   @require_vision
   @slow
   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        super().test_pipeline_image_classification()




def  _lowerCAmelCase				(				)  ->      List[str]:
     '''simple docstring'''







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




@require_torch
@require_vision
class    lowerCamelCase__  (   unittest.TestCase     ):



   @cached_property
   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        return AutoImageProcessor.from_pretrained("""google/efficientnet-b7"""     ) if is_vision_available() else None




   @slow
   def  _UpperCamelCase		(    self     )				->     int:
        """simple docstring"""





        _UpperCamelCase  :str       =EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""     ).to(lowerCAmelCase__     )

        _UpperCamelCase  :Optional[Any]       =self.default_image_processor
        _UpperCamelCase  :Any       =prepare_img()
        _UpperCamelCase  :Union[str, Any]       =image_processor(images=lowerCAmelCase__					,      return_tensors="""pt"""     ).to(lowerCAmelCase__     )

        # forward pass
        with torch.no_grad():
             _UpperCamelCase  :List[Any]       =model(**lowerCAmelCase__     )

        # verify the logits
        _UpperCamelCase  :List[str]       =torch.Size((1, 1_000)     )
        self.assertEqual(outputs.logits.shape					,      lowerCAmelCase__     )

        _UpperCamelCase  :int       =torch.tensor([0.0001, 0.0002, 0.0002]     ).to(lowerCAmelCase__     )
        self.assertTrue(torch.allclose(outputs.logits[0, :3]					,      lowerCAmelCase__					,      atol=1e-4     )     )







def    a__    (	A       ):
   return int(A       ) if x - int(A       ) >= 0 else int(A       ) - 1


if __name__ == "__main__":
 import doctest

 doctest.testmod()


