






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__=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				,    ):




									"""simple docstring"""

									__UpperCamelCase :   Tuple									=parent
									__UpperCamelCase :   Dict									=batch_size
									__UpperCamelCase :   Any									=image_size
									__UpperCamelCase :   List[str]									=num_channels
									__UpperCamelCase :   List[str]									=kernel_sizes
									__UpperCamelCase :   List[Any]									=in_channels
									__UpperCamelCase :   List[Any]									=out_channels
									__UpperCamelCase :   List[str]									=strides
									__UpperCamelCase :   Any									=num_block_repeats
									__UpperCamelCase :   Tuple									=expand_ratios
									__UpperCamelCase :   Any									=is_training
									__UpperCamelCase :   List[str]									=hidden_act
									__UpperCamelCase :   str									=num_labels
									__UpperCamelCase :   List[Any]									=use_labels


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   Dict									=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

									__UpperCamelCase :   List[Any]									=self.get_config()
									return config, pixel_values, labels


				def  __lowercase				(					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  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   List[str]									=EfficientNetModel(config=A_       )
									model.to(A_       )
									model.eval()
									__UpperCamelCase :   Optional[Any]									=model(A_       )
									# 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  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[Any]									=EfficientNetForImageClassification(A_       )
									model.to(A_       )
									model.eval()
									__UpperCamelCase :   Union[str, Any]									=model(A_				,    labels=A_       )
									self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.num_labels)       )







				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   List[str]									=self.prepare_config_and_inputs()
									__UpperCamelCase						,							__UpperCamelCase						,							__UpperCamelCase :   int									=config_and_inputs
									__UpperCamelCase :   Dict									={'pixel_values': pixel_values}
									return config, inputs_dict




@require_torch
class 							__A	(     _SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	unittest.TestCase					):





				"""simple docstring"""







				UpperCamelCase__					: Dict     					=(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
				UpperCamelCase__					: Dict     					=(
				    {"feature-extraction": EfficientNetModel, "image-classification": EfficientNetForImageClassification}
				    if is_torch_available()
				    else {}
				)

				UpperCamelCase__					: int     					=False
				UpperCamelCase__					: Optional[int]     					=False
				UpperCamelCase__					: Optional[Any]     					=False
				UpperCamelCase__					: Any     					=False
				UpperCamelCase__					: str     					=False


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   List[str]									=EfficientNetModelTester(self       )
									__UpperCamelCase :   Optional[Any]									=ConfigTester(
									    self				,    config_class=A_				,    has_text_modality=A_				,    hidden_size=37       )


				def  __lowercase				(					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  __lowercase				(					self       ):




									"""simple docstring"""

									return


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




									"""simple docstring"""

									pass


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




									"""simple docstring"""

									pass


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




									"""simple docstring"""

									pass


				def  __lowercase				(					self       ):




									"""simple docstring"""

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

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

														__UpperCamelCase :   List[str]									=['pixel_values']
														self.assertListEqual(arg_names[:1]				,    A_       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

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


				def  __lowercase				(					self       ):




									"""simple docstring"""

									def check_hidden_states_output(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):
														__UpperCamelCase :   Dict									=model_class(A_       )
														model.to(A_       )
														model.eval()

														with torch.no_grad():
																			__UpperCamelCase :   List[str]									=model(**self._prepare_for_class(A_				,    A_       )       )

														__UpperCamelCase :   Dict									=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
														__UpperCamelCase :   str									=sum(config.num_block_repeats       ) * 4
														self.assertEqual(len(A_       )				,    A_       )

														# 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 :   Dict									=self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
														__UpperCamelCase :   Dict									=True
														check_hidden_states_output(A_				,    A_				,    A_       )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														__UpperCamelCase :   Union[str, Any]									=True

														check_hidden_states_output(A_				,    A_				,    A_       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   Union[str, Any]									=self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*A_       )


				@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'       )
				def  __lowercase				(					self       ):




									"""simple docstring"""

									pass


				@slow
				def  __lowercase				(					self       ):




									"""simple docstring"""

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







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




									"""simple docstring"""

									super().test_pipeline_image_classification()






def 				A	(			)	->		Optional[int]:
					__UpperCamelCase :   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  __lowercase				(					self       ):




									"""simple docstring"""

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







				@slow
				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   Tuple									=EfficientNetForImageClassification.from_pretrained('google/efficientnet-b7'       ).to(A_       )

									__UpperCamelCase :   Dict									=self.default_image_processor
									__UpperCamelCase :   int									=prepare_img()
									__UpperCamelCase :   Tuple									=image_processor(images=A_				,    return_tensors='pt'       ).to(A_       )

									# forward pass
									with torch.no_grad():
														__UpperCamelCase :   str									=model(**A_       )

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

									__UpperCamelCase :   Tuple									=torch.tensor([0.0_001, 0.0_002, 0.0_002]       ).to(A_       )
									self.assertTrue(torch.allclose(outputs.logits[0, :3]				,    A_				,    atol=1E-4       )       )



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_UpperCAmelCase   :					int    =			{"configuration_levit": ["LEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LevitConfig", "LevitOnnxConfig"]}

try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_UpperCAmelCase   :					Optional[Any]    =			["LevitFeatureExtractor"]
					_UpperCAmelCase   :					Optional[int]    =			["LevitImageProcessor"]

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_UpperCAmelCase   :					Optional[int]    =			[
					    "LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
					    "LevitForImageClassification",
					    "LevitForImageClassificationWithTeacher",
					    "LevitModel",
					    "LevitPreTrainedModel",
					]


if TYPE_CHECKING:
					from .configuration_levit import LEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, LevitConfig, LevitOnnxConfig

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .feature_extraction_levit import LevitFeatureExtractor
										from .image_processing_levit import LevitImageProcessor

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_levit import (
										    LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
										    LevitForImageClassification,
										    LevitForImageClassificationWithTeacher,
										    LevitModel,
										    LevitPreTrainedModel,
										)
else:
					import sys

					_UpperCAmelCase   :					Optional[Any]    =			_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
