
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      :			Dict      ,							UpperCamelCase__      :			Any      ,							UpperCamelCase__      :			List[str]=13      ,							UpperCamelCase__      :			Optional[int]=32      ,							UpperCamelCase__      :			Optional[int]=3      ,							UpperCamelCase__      :			Union[str, Any]=[3, 3, 5]      ,							UpperCamelCase__      :			Optional[int]=[32, 16, 24]      ,							UpperCamelCase__      :			Optional[Any]=[16, 24, 40]      ,							UpperCamelCase__      :			str=[1, 1, 2]      ,							UpperCamelCase__      :			Union[str, Any]=[1, 1, 2]      ,							UpperCamelCase__      :			Optional[Any]=[1, 6, 6]      ,							UpperCamelCase__      :			Any=True      ,							UpperCamelCase__      :			str=True      ,							UpperCamelCase__      :			Tuple=37      ,							UpperCamelCase__      :			Any="gelu"      ,							UpperCamelCase__      :			Dict=10      ,							)      ->     List[str]:







    """simple docstring"""






    __magic_name__    					=	parent
    __magic_name__    					=	batch_size
    __magic_name__    					=	image_size
    __magic_name__    					=	num_channels
    __magic_name__    					=	kernel_sizes
    __magic_name__    					=	in_channels
    __magic_name__    					=	out_channels
    __magic_name__    					=	strides
    __magic_name__    					=	num_block_repeats
    __magic_name__    					=	expand_ratios
    __magic_name__    					=	is_training
    __magic_name__    					=	hidden_act
    __magic_name__    					=	num_labels
    __magic_name__    					=	use_labels
  def 							_lowercase							(			self      :			str   )      ->     Union[str, Any]:







    """simple docstring"""






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

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

    __magic_name__    					=	self.get_config()
    return config, pixel_values, labels
  def 							_lowercase							(			self      :			List[Any]   )      ->     List[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 							_lowercase							(			self      :			int      ,							UpperCamelCase__      :			Dict      ,							UpperCamelCase__      :			Union[str, Any]      ,							UpperCamelCase__      :			int   )      ->     Optional[int]:







    """simple docstring"""






    __magic_name__    					=	EfficientNetModel(config=UpperCamelCase__   )
    model.to(UpperCamelCase__   )
    model.eval()
    __magic_name__    					=	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 							_lowercase							(			self      :			List[Any]      ,							UpperCamelCase__      :			Optional[int]      ,							UpperCamelCase__      :			Tuple      ,							UpperCamelCase__      :			Dict   )      ->     Optional[Any]:







    """simple docstring"""






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





  def 							_lowercase							(			self      :			List[str]   )      ->     Optional[int]:







    """simple docstring"""






    __magic_name__    					=	self.prepare_config_and_inputs()
    __magic_name__					,   __magic_name__					,   __magic_name__    					=	config_and_inputs
    __magic_name__    					=	{"""pixel_values""": pixel_values}
    return config, inputs_dict







@require_torch
class 	UpperCAmelCase_      (			_A  ,	_A  ,	unittest.TestCase					):


  '''simple docstring'''







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

  a__   	=		False
  a__   	=		False
  a__   	=		False
  a__   	=		False
  a__   	=		False
  def 							_lowercase							(			self      :			Tuple   )      ->     Union[str, Any]:







    """simple docstring"""






    __magic_name__    					=	EfficientNetModelTester(self   )
    __magic_name__    					=	ConfigTester(
        self      ,							config_class=UpperCamelCase__      ,							has_text_modality=UpperCamelCase__      ,							hidden_size=37   )
  def 							_lowercase							(			self      :			Any   )      ->     Optional[int]:







    """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      :			Any   )      ->     Dict:







    """simple docstring"""






    return
  @unittest.skip(reason="""EfficientNet does not use inputs_embeds"""   )
  def 							_lowercase							(			self      :			str   )      ->     str:







    """simple docstring"""






    pass
  @unittest.skip(reason="""EfficientNet does not support input and output embeddings"""   )
  def 							_lowercase							(			self      :			List[Any]   )      ->     Optional[int]:







    """simple docstring"""






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







    """simple docstring"""






    pass
  def 							_lowercase							(			self      :			Dict   )      ->     Dict:







    """simple docstring"""






    __magic_name__					,   __magic_name__    					=	self.model_tester.prepare_config_and_inputs_for_common()

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

      __magic_name__    					=	["""pixel_values"""]
      self.assertListEqual(arg_names[:1]      ,							UpperCamelCase__   )
  def 							_lowercase							(			self      :			Union[str, Any]   )      ->     Dict:







    """simple docstring"""






    __magic_name__    					=	self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCamelCase__   )
  def 							_lowercase							(			self      :			List[Any]   )      ->     int:







    """simple docstring"""






    def check_hidden_states_output(UpperCamelCase__      :			Dict      ,							UpperCamelCase__      :			List[str]      ,							UpperCamelCase__      :			Union[str, Any]   ):
      __magic_name__    					=	model_class(UpperCamelCase__   )
      model.to(UpperCamelCase__   )
      model.eval()

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

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

    __magic_name__					,   __magic_name__    					=	self.model_tester.prepare_config_and_inputs_for_common()

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

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

      check_hidden_states_output(UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__   )
  def 							_lowercase							(			self      :			Tuple   )      ->     Any:







    """simple docstring"""






    __magic_name__    					=	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 							_lowercase							(			self      :			Optional[Any]   )      ->     Optional[int]:







    """simple docstring"""






    pass
  @slow
  def 							_lowercase							(			self      :			int   )      ->     Union[str, Any]:







    """simple docstring"""






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





  @is_pipeline_test
  @require_vision
  @slow
  def 							_lowercase							(			self      :			str   )      ->     Optional[int]:







    """simple docstring"""






    super().test_pipeline_image_classification()







def a__   (	):






  '''simple docstring'''





  __magic_name__    					=	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
  return image





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


  '''simple docstring'''







  @cached_property
  def 							_lowercase							(			self      :			List[str]   )      ->     Optional[int]:







    """simple docstring"""






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





  @slow
  def 							_lowercase							(			self      :			Dict   )      ->     Optional[int]:







    """simple docstring"""






    __magic_name__    					=	EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""   ).to(UpperCamelCase__   )

    __magic_name__    					=	self.default_image_processor
    __magic_name__    					=	prepare_img()
    __magic_name__    					=	image_processor(images=UpperCamelCase__      ,							return_tensors="""pt"""   ).to(UpperCamelCase__   )

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

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

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



from itertools import compress, repeat
from math import ceil, sqrt

def a__   (	A_ ):






  '''simple docstring'''





  if num <= 2:
    return []
  if num == 3:
    return [2]

  # Odd sieve for numbers in range [3, num - 1]
  __magic_name__    					=	bytearray(b"""\x01""" ) * ((num >> 1) - 1)

  for i in range(3,					int(sqrt(A_ ) ) + 1,					2 ):
    if sieve[(i >> 1) - 1]:
      __magic_name__    					=	i**2
      __magic_name__    					=	repeat(
          0,					ceil((num - i_squared) / (i << 1) ) )

  return [2] + list(compress(range(3,					A_,					2 ),					A_ ) )


if __name__ == "__main__":
    import doctest

    doctest.testmod()

