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






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






      def 	__lowercase(     self					:   List[Any]   )  -> Dict:
           UpperCamelCase__							:  Any								=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

           UpperCamelCase__							:  Optional[Any]								=     self.get_config()
           return config, pixel_values, labels






      def 	__lowercase(     self					:   Any   )  -> Dict:
           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					:   Union[str, Any],		__lowerCamelCase					:   Union[str, Any],		__lowerCamelCase					:   Dict,		__lowerCamelCase					:   Union[str, Any]   )  -> int:
           UpperCamelCase__							:  Union[str, Any]								=     EfficientNetModel(config=lowercase_   )
           model.to(lowercase_   )
           model.eval()
           UpperCamelCase__							:  List[str]								=     model(lowercase_   )
           # 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					:   str,		__lowerCamelCase					:   List[Any],		__lowerCamelCase					:   int,		__lowerCamelCase					:   Optional[int]   )  -> Dict:
           UpperCamelCase__							:  Optional[int]								=     EfficientNetForImageClassification(lowercase_   )
           model.to(lowercase_   )
           model.eval()
           UpperCamelCase__							:  Any								=     model(lowercase_,		labels=lowercase_   )
           self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.num_labels)   )






      def 	__lowercase(     self					:   List[Any]   )  -> int:
           UpperCamelCase__							:  List[str]								=     self.prepare_config_and_inputs()
           UpperCamelCase__							:  int								=     config_and_inputs
           UpperCamelCase__							:  Union[str, Any]								=     {'''pixel_values''': pixel_values}
           return config, inputs_dict

@require_torch
class  UpperCamelCase__ ( __UpperCAmelCase							,						__UpperCAmelCase							,						unittest.TestCase			):
      a__   :     Any								=						(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
      a__   :     List[str]								=						(
          {'feature-extraction': EfficientNetModel, 'image-classification': EfficientNetForImageClassification}
          if is_torch_available()
          else {}
      )

      a__   :     int								=						False
      a__   :     Optional[Any]								=						False
      a__   :     List[str]								=						False
      a__   :     str								=						False
      a__   :     Optional[int]								=						False






      def 	__lowercase(     self					:   Dict   )  -> Dict:
           UpperCamelCase__							:  Optional[int]								=     EfficientNetModelTester(self   )
           UpperCamelCase__							:  List[str]								=     ConfigTester(
               self,		config_class=lowercase_,		has_text_modality=lowercase_,		hidden_size=37   )






      def 	__lowercase(     self					:   Tuple   )  -> 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 	__lowercase(     self					:   List[str]   )  -> Optional[Any]:
           return






      @unittest.skip(reason='''EfficientNet does not use inputs_embeds'''   )
      def 	__lowercase(     self					:   Union[str, Any]   )  -> List[str]:
           pass






      @unittest.skip(reason='''EfficientNet does not support input and output embeddings'''   )
      def 	__lowercase(     self					:   Dict   )  -> List[Any]:
           pass






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






      def 	__lowercase(     self					:   List[str]   )  -> Dict:
           UpperCamelCase__							:  str								=     self.model_tester.prepare_config_and_inputs_for_common()

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

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






      def 	__lowercase(     self					:   List[str]   )  -> Union[str, Any]:
           UpperCamelCase__							:  List[Any]								=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase_   )






      def 	__lowercase(     self					:   Optional[Any]   )  -> Tuple:

           def check_hidden_states_output(__lowerCamelCase					:   str,		__lowerCamelCase					:   List[Any],		__lowerCamelCase					:   Optional[Any]   ):
                UpperCamelCase__							:  Tuple								=     model_class(lowercase_   )
                model.to(lowercase_   )
                model.eval()

                with torch.no_grad():
                     UpperCamelCase__							:  Tuple								=     model(**self._prepare_for_class(lowercase_,		lowercase_   )   )

                UpperCamelCase__							:  List[Any]								=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
                UpperCamelCase__							:  str								=     sum(config.num_block_repeats   ) * 4
                self.assertEqual(len(lowercase_   ),		lowercase_   )

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

           for model_class in self.all_model_classes:
                UpperCamelCase__							:  Dict								=     True
                check_hidden_states_output(lowercase_,		lowercase_,		lowercase_   )

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

                check_hidden_states_output(lowercase_,		lowercase_,		lowercase_   )






      def 	__lowercase(     self					:   str   )  -> List[str]:
           UpperCamelCase__							:  Union[str, Any]								=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowercase_   )






      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
      def 	__lowercase(     self					:   Union[str, Any]   )  -> str:
           pass






      @slow
      def 	__lowercase(     self					:   List[Any]   )  -> Optional[Any]:

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






      @is_pipeline_test
      @require_vision
      @slow
      def 	__lowercase(     self					:   Optional[Any]   )  -> int:
           super().test_pipeline_image_classification()







def 						_lowercase       (     )  ->   Optional[Any]:





     '''simple docstring'''





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







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






      @cached_property
      def 	__lowercase(     self					:   List[str]   )  -> Tuple:
           return AutoImageProcessor.from_pretrained('''google/efficientnet-b7'''   ) if is_vision_available() else None






      @slow
      def 	__lowercase(     self					:   Dict   )  -> Any:
           UpperCamelCase__							:  Optional[Any]								=     EfficientNetForImageClassification.from_pretrained('''google/efficientnet-b7'''   ).to(lowercase_   )

           UpperCamelCase__							:  List[Any]								=     self.default_image_processor
           UpperCamelCase__							:  List[Any]								=     prepare_img()
           UpperCamelCase__							:  List[str]								=     image_processor(images=lowercase_,		return_tensors='''pt'''   ).to(lowercase_   )

           # forward pass
           with torch.no_grad():
                UpperCamelCase__							:  int								=     model(**lowercase_   )

           # verify the logits
           UpperCamelCase__							:  Optional[Any]								=     torch.Size((1, 10_00)   )
           self.assertEqual(outputs.logits.shape,		lowercase_   )

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








from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_SCREAMING_SNAKE_CASE :					Optional[Any]			=	{
    """configuration_layoutlm""": ["""LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LayoutLMConfig""", """LayoutLMOnnxConfig"""],
    """tokenization_layoutlm""": ["""LayoutLMTokenizer"""],
}

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _SCREAMING_SNAKE_CASE :					Dict			=	["""LayoutLMTokenizerFast"""]

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _SCREAMING_SNAKE_CASE :					List[str]			=	[
       """LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
       """LayoutLMForMaskedLM""",
       """LayoutLMForSequenceClassification""",
       """LayoutLMForTokenClassification""",
       """LayoutLMForQuestionAnswering""",
       """LayoutLMModel""",
       """LayoutLMPreTrainedModel""",
   ]

try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _SCREAMING_SNAKE_CASE :					str			=	[
       """TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
       """TFLayoutLMForMaskedLM""",
       """TFLayoutLMForSequenceClassification""",
       """TFLayoutLMForTokenClassification""",
       """TFLayoutLMForQuestionAnswering""",
       """TFLayoutLMMainLayer""",
       """TFLayoutLMModel""",
       """TFLayoutLMPreTrainedModel""",
   ]


if TYPE_CHECKING:
   from .configuration_layoutlm import LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMConfig, LayoutLMOnnxConfig
   from .tokenization_layoutlm import LayoutLMTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_layoutlm_fast import LayoutLMTokenizerFast

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_layoutlm import (
          LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
          LayoutLMForMaskedLM,
          LayoutLMForQuestionAnswering,
          LayoutLMForSequenceClassification,
          LayoutLMForTokenClassification,
          LayoutLMModel,
          LayoutLMPreTrainedModel,
      )
   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_tf_layoutlm import (
          TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFLayoutLMForMaskedLM,
          TFLayoutLMForQuestionAnswering,
          TFLayoutLMForSequenceClassification,
          TFLayoutLMForTokenClassification,
          TFLayoutLMMainLayer,
          TFLayoutLMModel,
          TFLayoutLMPreTrainedModel,
      )

else:
   import sys

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




