






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







      '''simple docstring'''

      def __init__(self,	lowerCamelCase_,	lowerCamelCase_=1_3,	lowerCamelCase_=3_2,	lowerCamelCase_=3,	lowerCamelCase_=[3, 3, 5],	lowerCamelCase_=[3_2, 1_6, 2_4],	lowerCamelCase_=[1_6, 2_4, 4_0],	lowerCamelCase_=[1, 1, 2],	lowerCamelCase_=[1, 1, 2],	lowerCamelCase_=[1, 6, 6],	lowerCamelCase_=True,	lowerCamelCase_=True,	lowerCamelCase_=3_7,	lowerCamelCase_="gelu",	lowerCamelCase_=1_0,	):

       '''simple docstring'''



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




      def      a__				(self   ):

       '''simple docstring'''



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

       lowerCamelCase__	:     Any								=		None
       if self.use_labels:
        lowerCamelCase__	:     Dict								=		ids_tensor([self.batch_size],	self.num_labels   )

       lowerCamelCase__	:     Union[str, Any]								=		self.get_config()
       return config, pixel_values, labels




      def      a__				(self   ):

       '''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      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[Any]								=		EfficientNetModel(config=lowerCamelCase__   )
       model.to(lowerCamelCase__   )
       model.eval()
       lowerCamelCase__	:     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      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     int								=		EfficientNetForImageClassification(lowerCamelCase__   )
       model.to(lowerCamelCase__   )
       model.eval()
       lowerCamelCase__	:     List[str]								=		model(lowerCamelCase__,	labels=lowerCamelCase__   )
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.num_labels)   )





      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		self.prepare_config_and_inputs()
       lowerCamelCase__							,	lowerCamelCase__							,	lowerCamelCase__	:     Union[str, Any]								=		config_and_inputs
       lowerCamelCase__	:     Optional[int]								=		{'pixel_values': pixel_values}
       return config, inputs_dict



@require_torch
class 						a_ (      __UpperCAmelCase    ,		__UpperCAmelCase    ,		unittest.TestCase					):







      '''simple docstring'''

      lowerCamelCase__			:							Union[str, Any]					=      (EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
      lowerCamelCase__			:							Optional[Any]					=      (
          {'feature-extraction': EfficientNetModel, 'image-classification': EfficientNetForImageClassification}
          if is_torch_available()
          else {}
      )

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




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[Any]								=		EfficientNetModelTester(self   )
       lowerCamelCase__	:     Optional[int]								=		ConfigTester(
           self,	config_class=lowerCamelCase__,	has_text_modality=lowerCamelCase__,	hidden_size=3_7   )




      def      a__				(self   ):

       '''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      a__				(self   ):

       '''simple docstring'''



       return




      @unittest.skip(reason='EfficientNet does not use inputs_embeds'   )
      def      a__				(self   ):

       '''simple docstring'''



       pass




      @unittest.skip(reason='EfficientNet does not support input and output embeddings'   )
      def      a__				(self   ):

       '''simple docstring'''



       pass




      @unittest.skip(reason='EfficientNet does not use feedforward chunking'   )
      def      a__				(self   ):

       '''simple docstring'''



       pass




      def      a__				(self   ):

       '''simple docstring'''



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

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

        lowerCamelCase__	:     str								=		['pixel_values']
        self.assertListEqual(arg_names[:1],	lowerCamelCase__   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase__   )




      def      a__				(self   ):

       '''simple docstring'''



       def check_hidden_states_output(lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):
        lowerCamelCase__	:     Tuple								=		model_class(lowerCamelCase__   )
        model.to(lowerCamelCase__   )
        model.eval()

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

        lowerCamelCase__	:     Any								=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
        lowerCamelCase__	:     Union[str, 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],	)

       lowerCamelCase__							,	lowerCamelCase__	:     Union[str, Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCamelCase__	:     int								=		True
        check_hidden_states_output(lowerCamelCase__,	lowerCamelCase__,	lowerCamelCase__   )

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

        check_hidden_states_output(lowerCamelCase__,	lowerCamelCase__,	lowerCamelCase__   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		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      a__				(self   ):

       '''simple docstring'''



       pass




      @slow
      def      a__				(self   ):

       '''simple docstring'''



       for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase__	:     str								=		EfficientNetModel.from_pretrained(lowerCamelCase__   )
        self.assertIsNotNone(lowerCamelCase__   )





      @is_pipeline_test
      @require_vision
      @slow
      def      a__				(self   ):

       '''simple docstring'''



       super().test_pipeline_image_classification()






def 			lowerCamelCase_    (		):
 lowerCamelCase__	:     Optional[int]								=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
 return image





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







      '''simple docstring'''

      @cached_property
      def      a__				(self   ):

       '''simple docstring'''



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





      @slow
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		EfficientNetForImageClassification.from_pretrained('google/efficientnet-b7'   ).to(lowerCamelCase__   )

       lowerCamelCase__	:     int								=		self.default_image_processor
       lowerCamelCase__	:     str								=		prepare_img()
       lowerCamelCase__	:     Union[str, Any]								=		image_processor(images=lowerCamelCase__,	return_tensors='pt'   ).to(lowerCamelCase__   )

       # forward pass
       with torch.no_grad():
        lowerCamelCase__	:     Optional[Any]								=		model(**lowerCamelCase__   )

       # verify the logits
       lowerCamelCase__	:     Dict								=		torch.Size((1, 1_0_0_0)   )
       self.assertEqual(outputs.logits.shape,	lowerCamelCase__   )

       lowerCamelCase__	:     Optional[Any]								=		torch.tensor([0.0_001, 0.0_002, 0.0_002]   ).to(lowerCamelCase__   )
       self.assertTrue(torch.allclose(outputs.logits[0, :3],	lowerCamelCase__,	atol=1e-4   )   )


"""simple docstring"""






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
						import PIL


lowerCAmelCase__    :    Tuple			=      logging.get_logger(__name__)
class 							snake_case			(					__UpperCAmelCase							):




					"""simple docstring"""

					snake_case__							       =					["pixel_values"]







					def __init__(							self  :      str       ,lowerCamelCase__  :      bool = True       ,lowerCamelCase__  :      Dict[str, int] = None       ,lowerCamelCase__  :      bool = True       ,lowerCamelCase__  :      Dict[str, int] = None       ,lowerCamelCase__  :      PILImageResampling = PILImageResampling.BICUBIC       ,lowerCamelCase__  :      bool = True       ,lowerCamelCase__  :      Union[int, float] = 1 / 255       ,lowerCamelCase__  :      bool = True       ,lowerCamelCase__  :      Optional[Union[float, List[float]]] = None       ,lowerCamelCase__  :      Optional[Union[float, List[float]]] = None       ,**lowerCamelCase__  :      List[Any]       ,):
									super().__init__(**lowerCamelCase__     )
									UpperCAmelCase__			 =				crop_size if crop_size is not None else {'height': 256, 'width': 256}
									UpperCAmelCase__			 =				get_size_dict(lowerCamelCase__       ,param_name='crop_size'     )
									UpperCAmelCase__			 =				size if size is not None else {'height': 224, 'width': 224}
									UpperCAmelCase__			 =				get_size_dict(lowerCamelCase__     )

									UpperCAmelCase__			 =				do_center_crop
									UpperCAmelCase__			 =				crop_size
									UpperCAmelCase__			 =				do_resize
									UpperCAmelCase__			 =				size
									UpperCAmelCase__			 =				resample
									UpperCAmelCase__			 =				do_rescale
									UpperCAmelCase__			 =				rescale_factor
									UpperCAmelCase__			 =				do_normalize
									UpperCAmelCase__			 =				image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
									UpperCAmelCase__			 =				image_std if image_std is not None else IMAGENET_DEFAULT_STD







					def 						__lowerCAmelCase		(							self  :      Optional[int]       ,lowerCamelCase__  :      np.ndarray       ,lowerCamelCase__  :      Dict[str, int]       ,lowerCamelCase__  :      Optional[int] = None       ,lowerCamelCase__  :      Optional[Union[str, ChannelDimension]] = None       ,**lowerCamelCase__  :      List[str]       ,):
									UpperCAmelCase__			 =				self.size if size is None else size
									UpperCAmelCase__			 =				get_size_dict(lowerCamelCase__     )
									UpperCAmelCase__			 =				get_size_dict(lowerCamelCase__       ,param_name='crop_size'     )

									UpperCAmelCase__ ,      UpperCAmelCase__			 =				get_image_size(lowerCamelCase__     )
									UpperCAmelCase__			 =				min(lowerCamelCase__       ,lowerCamelCase__     )
									UpperCAmelCase__			 =				(size['height'] / crop_size['height']) * min_dim
									UpperCAmelCase__			 =				(size['width'] / crop_size['width']) * min_dim
									return center_crop(lowerCamelCase__       ,size=(cropped_height, cropped_width)       ,data_format=lowerCamelCase__       ,**lowerCamelCase__     )







					def 						__lowerCAmelCase		(							self  :      Any       ,lowerCamelCase__  :      np.ndarray       ,lowerCamelCase__  :      Dict[str, int]       ,lowerCamelCase__  :      PILImageResampling = PIL.Image.BICUBIC       ,lowerCamelCase__  :      Optional[Union[str, ChannelDimension]] = None       ,**lowerCamelCase__  :      Any       ,):
									UpperCAmelCase__			 =				get_size_dict(lowerCamelCase__     )
									if "height" not in size or "width" not in size:
													raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'''     )
									return resize(
									    lowerCamelCase__       ,size=(size['height'], size['width'])       ,resample=lowerCamelCase__       ,data_format=lowerCamelCase__       ,**lowerCamelCase__     )







					def 						__lowerCAmelCase		(							self  :      Optional[int]       ,lowerCamelCase__  :      np.ndarray       ,lowerCamelCase__  :      Union[int, float]       ,lowerCamelCase__  :      Optional[Union[str, ChannelDimension]] = None       ,**lowerCamelCase__  :      int       ,):
									return rescale(lowerCamelCase__       ,scale=lowerCamelCase__       ,data_format=lowerCamelCase__       ,**lowerCamelCase__     )







					def 						__lowerCAmelCase		(							self  :      int       ,lowerCamelCase__  :      np.ndarray       ,lowerCamelCase__  :      Union[float, List[float]]       ,lowerCamelCase__  :      Union[float, List[float]]       ,lowerCamelCase__  :      Optional[Union[str, ChannelDimension]] = None       ,**lowerCamelCase__  :      List[Any]       ,):
									return normalize(lowerCamelCase__       ,mean=lowerCamelCase__       ,std=lowerCamelCase__       ,data_format=lowerCamelCase__       ,**lowerCamelCase__     )







					def 						__lowerCAmelCase		(							self  :      Optional[Any]       ,lowerCamelCase__  :      ImageInput       ,lowerCamelCase__  :      Optional[bool] = None       ,lowerCamelCase__  :      Optional[Dict[str, int]] = None       ,lowerCamelCase__  :      Optional[bool] = None       ,lowerCamelCase__  :      Optional[Dict[str, int]] = None       ,lowerCamelCase__  :      PILImageResampling = None       ,lowerCamelCase__  :      Optional[bool] = None       ,lowerCamelCase__  :      Optional[float] = None       ,lowerCamelCase__  :      Optional[bool] = None       ,lowerCamelCase__  :      Optional[Union[float, List[float]]] = None       ,lowerCamelCase__  :      Optional[Union[float, List[float]]] = None       ,lowerCamelCase__  :      Optional[Union[str, TensorType]] = None       ,lowerCamelCase__  :      ChannelDimension = ChannelDimension.FIRST       ,**lowerCamelCase__  :      Optional[int]       ,):
									UpperCAmelCase__			 =				do_center_crop if do_center_crop is not None else self.do_center_crop
									UpperCAmelCase__			 =				crop_size if crop_size is not None else self.crop_size
									UpperCAmelCase__			 =				get_size_dict(lowerCamelCase__       ,param_name='crop_size'     )
									UpperCAmelCase__			 =				do_resize if do_resize is not None else self.do_resize
									UpperCAmelCase__			 =				size if size is not None else self.size
									UpperCAmelCase__			 =				get_size_dict(lowerCamelCase__     )
									UpperCAmelCase__			 =				resample if resample is not None else self.resample
									UpperCAmelCase__			 =				do_rescale if do_rescale is not None else self.do_rescale
									UpperCAmelCase__			 =				rescale_factor if rescale_factor is not None else self.rescale_factor
									UpperCAmelCase__			 =				do_normalize if do_normalize is not None else self.do_normalize
									UpperCAmelCase__			 =				image_mean if image_mean is not None else self.image_mean
									UpperCAmelCase__			 =				image_std if image_std is not None else self.image_std

									UpperCAmelCase__			 =				make_list_of_images(lowerCamelCase__     )

									if not valid_images(lowerCamelCase__     ):
													raise ValueError(
													    'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
													    'torch.Tensor, tf.Tensor or jax.ndarray.'     )

									if do_center_crop and crop_size is None:
													raise ValueError('If `do_center_crop` is set to `True`, `crop_size` must be provided.'     )

									if do_resize and size is None:
													raise ValueError('Size must be specified if do_resize is True.'     )

									if do_rescale and rescale_factor is None:
													raise ValueError('Rescale factor must be specified if do_rescale is True.'     )

									if do_normalize and (image_mean is None or image_std is None):
													raise ValueError('Image mean and image standard deviation must be specified if do_normalize is True.'     )

									# All transformations expect numpy arrays.
									UpperCAmelCase__			 =				[to_numpy_array(lowerCamelCase__     ) for image in images]

									if do_center_crop:
													UpperCAmelCase__			 =				[self.center_crop(lowerCamelCase__       ,lowerCamelCase__       ,size=lowerCamelCase__     ) for image in images]

									if do_resize:
													UpperCAmelCase__			 =				[self.resize(image=lowerCamelCase__       ,size=lowerCamelCase__       ,resample=lowerCamelCase__     ) for image in images]

									if do_rescale:
													UpperCAmelCase__			 =				[self.rescale(image=lowerCamelCase__       ,scale=lowerCamelCase__     ) for image in images]

									if do_normalize:
													UpperCAmelCase__			 =				[self.normalize(image=lowerCamelCase__       ,mean=lowerCamelCase__       ,std=lowerCamelCase__     ) for image in images]

									UpperCAmelCase__			 =				[to_channel_dimension_format(lowerCamelCase__       ,lowerCamelCase__     ) for image in images]

									UpperCAmelCase__			 =				{'pixel_values': images}
									return BatchFeature(data=lowerCamelCase__       ,tensor_type=lowerCamelCase__     )



