



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			:



       def __init__(						self				:	Dict	,						__SCREAMING_SNAKE_CASE				:	int	,						__SCREAMING_SNAKE_CASE				:	Optional[int]=13	,						__SCREAMING_SNAKE_CASE				:	Optional[Any]=32	,						__SCREAMING_SNAKE_CASE				:	int=3	,						__SCREAMING_SNAKE_CASE				:	List[str]=[3, 3, 5]	,						__SCREAMING_SNAKE_CASE				:	str=[32, 16, 24]	,						__SCREAMING_SNAKE_CASE				:	Optional[int]=[16, 24, 40]	,						__SCREAMING_SNAKE_CASE				:	Dict=[1, 1, 2]	,						__SCREAMING_SNAKE_CASE				:	Tuple=[1, 1, 2]	,						__SCREAMING_SNAKE_CASE				:	Union[str, Any]=[1, 6, 6]	,						__SCREAMING_SNAKE_CASE				:	Tuple=True	,						__SCREAMING_SNAKE_CASE				:	List[Any]=True	,						__SCREAMING_SNAKE_CASE				:	Optional[Any]=37	,						__SCREAMING_SNAKE_CASE				:	Dict="gelu"	,						__SCREAMING_SNAKE_CASE				:	int=10	,						):


           '''simple docstring'''

           __a					=							parent
           __a					=							batch_size
           __a					=							image_size
           __a					=							num_channels
           __a					=							kernel_sizes
           __a					=							in_channels
           __a					=							out_channels
           __a					=							strides
           __a					=							num_block_repeats
           __a					=							expand_ratios
           __a					=							is_training
           __a					=							hidden_act
           __a					=							num_labels
           __a					=							use_labels



       def 						_lowerCamelCase     (						self				:	List[Any]):


           '''simple docstring'''

           __a					=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

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



       def 						_lowerCamelCase     (						self				:	str):


           '''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 						_lowerCamelCase     (						self				:	List[Any]	,						__SCREAMING_SNAKE_CASE				:	int	,						__SCREAMING_SNAKE_CASE				:	Any	,						__SCREAMING_SNAKE_CASE				:	str):


           '''simple docstring'''

           __a					=							EfficientNetModel(config=lowercase_)
           model.to(lowercase_)
           model.eval()
           __a					=							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 						_lowerCamelCase     (						self				:	List[str]	,						__SCREAMING_SNAKE_CASE				:	Tuple	,						__SCREAMING_SNAKE_CASE				:	Optional[int]	,						__SCREAMING_SNAKE_CASE				:	Optional[int]):


           '''simple docstring'''

           __a					=							EfficientNetForImageClassification(lowercase_)
           model.to(lowercase_)
           model.eval()
           __a					=							model(lowercase_	,						labels=lowercase_)
           self.parent.assertEqual(result.logits.shape	,						(self.batch_size, self.num_labels))





       def 						_lowerCamelCase     (						self				:	Union[str, Any]):


           '''simple docstring'''

           __a					=							self.prepare_config_and_inputs()
           __a					=							config_and_inputs
           __a					=							{'pixel_values': pixel_values}
           return config, inputs_dict


@require_torch
class        _A			(      snake_case_ ,snake_case_ ,unittest.TestCase       ):
       UpperCamelCase__    :       int		   =		(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
       UpperCamelCase__    :       str		   =		(
           {'feature-extraction': EfficientNetModel, 'image-classification': EfficientNetForImageClassification}
           if is_torch_available()
           else {}
       )

       UpperCamelCase__    :       Dict		   =		False
       UpperCamelCase__    :       str		   =		False
       UpperCamelCase__    :       List[str]		   =		False
       UpperCamelCase__    :       Dict		   =		False
       UpperCamelCase__    :       str		   =		False



       def 						_lowerCamelCase     (						self				:	List[str]):


           '''simple docstring'''

           __a					=							EfficientNetModelTester(self)
           __a					=							ConfigTester(
               self	,						config_class=lowercase_	,						has_text_modality=lowercase_	,						hidden_size=37)



       def 						_lowerCamelCase     (						self				:	List[str]):


           '''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 						_lowerCamelCase     (						self				:	Optional[int]):


           '''simple docstring'''

           return



       @unittest.skip(reason='''EfficientNet does not use inputs_embeds''')
       def 						_lowerCamelCase     (						self				:	Optional[int]):


           '''simple docstring'''

           pass



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


           '''simple docstring'''

           pass



       @unittest.skip(reason='''EfficientNet does not use feedforward chunking''')
       def 						_lowerCamelCase     (						self				:	Optional[Any]):


           '''simple docstring'''

           pass



       def 						_lowerCamelCase     (						self				:	List[str]):


           '''simple docstring'''

           __a					=							self.model_tester.prepare_config_and_inputs_for_common()

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

               __a					=							['pixel_values']
               self.assertListEqual(arg_names[:1]	,						lowercase_)



       def 						_lowerCamelCase     (						self				:	int):


           '''simple docstring'''

           __a					=							self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase_)



       def 						_lowerCamelCase     (						self				:	Union[str, Any]):


           '''simple docstring'''

           def check_hidden_states_output(__SCREAMING_SNAKE_CASE				:	Optional[Any]	,						__SCREAMING_SNAKE_CASE				:	Optional[int]	,						__SCREAMING_SNAKE_CASE				:	str):
               __a					=							model_class(lowercase_)
               model.to(lowercase_)
               model.eval()

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

               __a					=							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
               __a					=							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]	,						)

           __a					=							self.model_tester.prepare_config_and_inputs_for_common()

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

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

               check_hidden_states_output(lowercase_	,						lowercase_	,						lowercase_)



       def 						_lowerCamelCase     (						self				:	List[Any]):


           '''simple docstring'''

           __a					=							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 						_lowerCamelCase     (						self				:	str):


           '''simple docstring'''

           pass



       @slow
       def 						_lowerCamelCase     (						self				:	Optional[int]):


           '''simple docstring'''

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





       @is_pipeline_test
       @require_vision
       @slow
       def 						_lowerCamelCase     (						self				:	List[str]):


           '''simple docstring'''

           super().test_pipeline_image_classification()





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

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



       @cached_property
       def 						_lowerCamelCase     (						self				:	Union[str, Any]):


           '''simple docstring'''

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





       @slow
       def 						_lowerCamelCase     (						self				:	Tuple):


           '''simple docstring'''

           __a					=							EfficientNetForImageClassification.from_pretrained('''google/efficientnet-b7''').to(lowercase_)

           __a					=							self.default_image_processor
           __a					=							prepare_img()
           __a					=							image_processor(images=lowercase_	,						return_tensors='''pt''').to(lowercase_)

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

           # verify the logits
           __a					=							torch.Size((1, 1_000))
           self.assertEqual(outputs.logits.shape	,						lowercase_)

           __a					=							torch.tensor([0.00_01, 0.00_02, 0.00_02]).to(lowercase_)
           self.assertTrue(torch.allclose(outputs.logits[0, :3]	,						lowercase_	,						atol=1E-4))













"""simple docstring"""


import numpy as np

_UpperCamelCase :    int      =			[
    ["""a""", """b""", """c""", """d""", """e"""],
    ["""f""", """g""", """h""", """i""", """k"""],
    ["""l""", """m""", """n""", """o""", """p"""],
    ["""q""", """r""", """s""", """t""", """u"""],
    ["""v""", """w""", """x""", """y""", """z"""],
]






class __a :



  def __init__(self	:		Any )		->				None:
   __A						:							Any      =						np.array(lowercase_ )



  def     A_					(self	:		Dict					,      lowercase_	:		str )		->				np.ndarray:
   __A     ,       __A						:							Any      =						np.where(letter == self.SQUARE )
   __A						:							Tuple      =						np.concatenate([indexa + 1, indexa + 1] )
   return indexes



  def     A_					(self	:		Tuple					,      lowercase_	:		int					,      lowercase_	:		int )		->				str:
   return self.SQUARE[indexa - 1, indexa - 1]



  def     A_					(self	:		Union[str, Any]					,      lowercase_	:		str )		->				str:
   __A						:							Any      =						message.lower()
   __A						:							Optional[Any]      =						message.replace('j'					,      'i' )

   __A						:							Union[str, Any]      =						''
   for letter_index in range(len(lowercase_ ) ):
    if message[letter_index] != " ":
     __A						:							Union[str, Any]      =						self.letter_to_numbers(message[letter_index] )
     __A						:							Union[str, Any]      =						encoded_message + str(numbers[0] ) + str(numbers[1] )
    elif message[letter_index] == " ":
     __A						:							Optional[Any]      =						encoded_message + ' '

   return encoded_message



  def     A_					(self	:		Dict					,      lowercase_	:		str )		->				str:
   __A						:							List[str]      =						message.replace(' '					,      '  ' )
   __A						:							List[Any]      =						''
   for numbers_index in range(int(len(lowercase_ ) / 2 ) ):
    if message[numbers_index * 2] != " ":
     __A						:							Any      =						message[numbers_index * 2]
     __A						:							Tuple      =						message[numbers_index * 2 + 1]

     __A						:							Dict      =						self.numbers_to_letter(int(lowercase_ )					,      int(lowercase_ ) )
     __A						:							Union[str, Any]      =						decoded_message + letter
    elif message[numbers_index * 2] == " ":
     __A						:							int      =						decoded_message + ' '

   return decoded_message





