

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  UpperCamelCase_      :


  """simple docstring"""



  def __init__(						self     :					List[str]  ,	A_     :					List[str]  ,	A_     :					Union[str, Any]=13  ,	A_     :					Union[str, Any]=32  ,	A_     :					Optional[Any]=3  ,	A_     :					Optional[int]=[3, 3, 5]  ,	A_     :					List[Any]=[32, 16, 24]  ,	A_     :					int=[16, 24, 40]  ,	A_     :					Tuple=[1, 1, 2]  ,	A_     :					List[Any]=[1, 1, 2]  ,	A_     :					List[Any]=[1, 6, 6]  ,	A_     :					Dict=True  ,	A_     :					str=True  ,	A_     :					Optional[Any]=37  ,	A_     :					str="gelu"  ,	A_     :					List[Any]=10  ,	)       ->			int:
      SCREAMING_SNAKE_CASE__         =    parent
      SCREAMING_SNAKE_CASE__         =    batch_size
      SCREAMING_SNAKE_CASE__         =    image_size
      SCREAMING_SNAKE_CASE__         =    num_channels
      SCREAMING_SNAKE_CASE__         =    kernel_sizes
      SCREAMING_SNAKE_CASE__         =    in_channels
      SCREAMING_SNAKE_CASE__         =    out_channels
      SCREAMING_SNAKE_CASE__         =    strides
      SCREAMING_SNAKE_CASE__         =    num_block_repeats
      SCREAMING_SNAKE_CASE__         =    expand_ratios
      SCREAMING_SNAKE_CASE__         =    is_training
      SCREAMING_SNAKE_CASE__         =    hidden_act
      SCREAMING_SNAKE_CASE__         =    num_labels
      SCREAMING_SNAKE_CASE__         =    use_labels



  def   _UpperCamelCase     (						self     :					Optional[Any]						)       ->			str:
      SCREAMING_SNAKE_CASE__         =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

      SCREAMING_SNAKE_CASE__         =    None
      if self.use_labels:
          SCREAMING_SNAKE_CASE__         =    ids_tensor([self.batch_size]  ,	self.num_labels						)

      SCREAMING_SNAKE_CASE__         =    self.get_config()
      return config, pixel_values, labels



  def   _UpperCamelCase     (						self     :					Dict						)       ->			Tuple:
      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     :					Optional[Any]  ,	A_     :					Optional[Any]  ,	A_     :					Any  ,	A_     :					Dict						)       ->			Optional[Any]:
      SCREAMING_SNAKE_CASE__         =    EfficientNetModel(config=UpperCAmelCase_						)
      model.to(UpperCAmelCase_						)
      model.eval()
      SCREAMING_SNAKE_CASE__         =    model(UpperCAmelCase_						)
      # 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     :					str  ,	A_     :					Optional[Any]  ,	A_     :					Optional[int]  ,	A_     :					Tuple						)       ->			Union[str, Any]:
      SCREAMING_SNAKE_CASE__         =    EfficientNetForImageClassification(UpperCAmelCase_						)
      model.to(UpperCAmelCase_						)
      model.eval()
      SCREAMING_SNAKE_CASE__         =    model(UpperCAmelCase_  ,	labels=UpperCAmelCase_						)
      self.parent.assertEqual(result.logits.shape  ,	(self.batch_size, self.num_labels)						)







  def   _UpperCamelCase     (						self     :					Optional[Any]						)       ->			List[Any]:
      SCREAMING_SNAKE_CASE__         =    self.prepare_config_and_inputs()
      SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__         =    config_and_inputs
      SCREAMING_SNAKE_CASE__         =    {"pixel_values": pixel_values}
      return config, inputs_dict







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


  """simple docstring"""
  SCREAMING_SNAKE_CASE__					:			Optional[Any]					    =   (EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE__					:			Tuple					    =   (
      {"""feature-extraction""": EfficientNetModel, """image-classification""": EfficientNetForImageClassification}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE__					:			Dict					    =   False
  SCREAMING_SNAKE_CASE__					:			Union[str, Any]					    =   False
  SCREAMING_SNAKE_CASE__					:			Dict					    =   False
  SCREAMING_SNAKE_CASE__					:			List[Any]					    =   False
  SCREAMING_SNAKE_CASE__					:			Tuple					    =   False



  def   _UpperCamelCase     (						self     :					Dict						)       ->			Optional[Any]:
      SCREAMING_SNAKE_CASE__         =    EfficientNetModelTester(self						)
      SCREAMING_SNAKE_CASE__         =    ConfigTester(
          self  ,	config_class=UpperCAmelCase_  ,	has_text_modality=UpperCAmelCase_  ,	hidden_size=37						)



  def   _UpperCamelCase     (						self     :					str						)       ->			Union[str, Any]:
      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     :					List[Any]						)       ->			int:
      return



  @unittest.skip(reason="EfficientNet does not use inputs_embeds"						)
  def   _UpperCamelCase     (						self     :					Optional[int]						)       ->			Union[str, Any]:
      pass



  @unittest.skip(reason="EfficientNet does not support input and output embeddings"						)
  def   _UpperCamelCase     (						self     :					Union[str, Any]						)       ->			Union[str, Any]:
      pass



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



  def   _UpperCamelCase     (						self     :					List[str]						)       ->			str:
      SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs_for_common()

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

          SCREAMING_SNAKE_CASE__         =    ["pixel_values"]
          self.assertListEqual(arg_names[:1]  ,	UpperCAmelCase_						)



  def   _UpperCamelCase     (						self     :					Optional[Any]						)       ->			Dict:
      SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*UpperCAmelCase_						)



  def   _UpperCamelCase     (						self     :					Dict						)       ->			str:
      def check_hidden_states_output(A_     :					Tuple  ,	A_     :					Dict  ,	A_     :					int						):
          SCREAMING_SNAKE_CASE__         =    model_class(UpperCAmelCase_						)
          model.to(UpperCAmelCase_						)
          model.eval()

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

          SCREAMING_SNAKE_CASE__         =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
          SCREAMING_SNAKE_CASE__         =    sum(config.num_block_repeats						) * 4
          self.assertEqual(len(UpperCAmelCase_						)  ,	UpperCAmelCase_						)

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

      SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs_for_common()

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

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

          check_hidden_states_output(UpperCAmelCase_  ,	UpperCAmelCase_  ,	UpperCAmelCase_						)



  def   _UpperCamelCase     (						self     :					str						)       ->			Dict:
      SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_						)



  @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
  def   _UpperCamelCase     (						self     :					Optional[int]						)       ->			List[Any]:
      pass



  @slow
  def   _UpperCamelCase     (						self     :					List[str]						)       ->			List[str]:
      for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          SCREAMING_SNAKE_CASE__         =    EfficientNetModel.from_pretrained(UpperCAmelCase_						)
          self.assertIsNotNone(UpperCAmelCase_						)







  @is_pipeline_test
  @require_vision
  @slow
  def   _UpperCamelCase     (						self     :					str						)       ->			List[str]:
      super().test_pipeline_image_classification()





def 				__a							(       ):
    SCREAMING_SNAKE_CASE__         =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
    return image







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


  """simple docstring"""



  @cached_property
  def   _UpperCamelCase     (						self     :					Tuple						)       ->			Tuple:
      return AutoImageProcessor.from_pretrained("google/efficientnet-b7"						) if is_vision_available() else None







  @slow
  def   _UpperCamelCase     (						self     :					Any						)       ->			str:
      SCREAMING_SNAKE_CASE__         =    EfficientNetForImageClassification.from_pretrained("google/efficientnet-b7"						).to(UpperCAmelCase_						)

      SCREAMING_SNAKE_CASE__         =    self.default_image_processor
      SCREAMING_SNAKE_CASE__         =    prepare_img()
      SCREAMING_SNAKE_CASE__         =    image_processor(images=UpperCAmelCase_  ,	return_tensors="pt"						).to(UpperCAmelCase_						)

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

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

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








from typing import TYPE_CHECKING

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


UpperCAmelCase_    ={"""configuration_vilt""": ["""VILT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViltConfig"""]}

try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCAmelCase_    =["""ViltFeatureExtractor"""]
		UpperCAmelCase_    =["""ViltImageProcessor"""]
		UpperCAmelCase_    =["""ViltProcessor"""]

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCAmelCase_    =[
		    """VILT_PRETRAINED_MODEL_ARCHIVE_LIST""",
		    """ViltForImageAndTextRetrieval""",
		    """ViltForImagesAndTextClassification""",
		    """ViltForTokenClassification""",
		    """ViltForMaskedLM""",
		    """ViltForQuestionAnswering""",
		    """ViltLayer""",
		    """ViltModel""",
		    """ViltPreTrainedModel""",
		]


if TYPE_CHECKING:
		from .configuration_vilt import VILT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViltConfig

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_vilt import ViltFeatureExtractor
				from .image_processing_vilt import ViltImageProcessor
				from .processing_vilt import ViltProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_vilt import (
				    VILT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    ViltForImageAndTextRetrieval,
				    ViltForImagesAndTextClassification,
				    ViltForMaskedLM,
				    ViltForQuestionAnswering,
				    ViltForTokenClassification,
				    ViltLayer,
				    ViltModel,
				    ViltPreTrainedModel,
				)


else:
		import sys

		UpperCAmelCase_    =_LazyModule(__name__, globals()["""__file__"""], _import_structure)



