





'''simple docstring'''

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







					"""simple docstring"""






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







							"""simple docstring"""
							__UpperCAmelCase     :				str					   =			parent
							__UpperCAmelCase     :				Optional[int]					   =			batch_size
							__UpperCAmelCase     :				Optional[Any]					   =			image_size
							__UpperCAmelCase     :				str					   =			num_channels
							__UpperCAmelCase     :				str					   =			kernel_sizes
							__UpperCAmelCase     :				Any					   =			in_channels
							__UpperCAmelCase     :				Dict					   =			out_channels
							__UpperCAmelCase     :				Union[str, Any]					   =			strides
							__UpperCAmelCase     :				List[Any]					   =			num_block_repeats
							__UpperCAmelCase     :				Dict					   =			expand_ratios
							__UpperCAmelCase     :				Any					   =			is_training
							__UpperCAmelCase     :				Tuple					   =			hidden_act
							__UpperCAmelCase     :				Optional[int]					   =			num_labels
							__UpperCAmelCase     :				Union[str, Any]					   =			use_labels
					def 						lowerCamelCase_					(					self    :	Union[str, Any]						):







							"""simple docstring"""
							__UpperCAmelCase     :				Dict					   =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

							__UpperCAmelCase     :				str					   =			None
							if self.use_labels:
									__UpperCAmelCase     :				Dict					   =			ids_tensor([self.batch_size]						,     self.num_labels						)

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







							"""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    :	Optional[int]						,     UpperCAmelCase_    :	List[str]						,     UpperCAmelCase_    :	Optional[Any]						,     UpperCAmelCase_    :	List[str]						):







							"""simple docstring"""
							__UpperCAmelCase     :				Optional[Any]					   =			EfficientNetModel(config=_UpperCAmelCase						)
							model.to(_UpperCAmelCase						)
							model.eval()
							__UpperCAmelCase     :				Optional[int]					   =			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 						lowerCamelCase_					(					self    :	Dict						,     UpperCAmelCase_    :	Union[str, Any]						,     UpperCAmelCase_    :	str						,     UpperCAmelCase_    :	Tuple						):







							"""simple docstring"""
							__UpperCAmelCase     :				List[str]					   =			EfficientNetForImageClassification(_UpperCAmelCase						)
							model.to(_UpperCAmelCase						)
							model.eval()
							__UpperCAmelCase     :				str					   =			model(_UpperCAmelCase						,     labels=_UpperCAmelCase						)
							self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.num_labels)						)






					def 						lowerCamelCase_					(					self    :	Any						):







							"""simple docstring"""
							__UpperCAmelCase     :				Optional[Any]					   =			self.prepare_config_and_inputs()
							__UpperCAmelCase   ,       __UpperCAmelCase   ,       __UpperCAmelCase     :				Any					   =			config_and_inputs
							__UpperCAmelCase     :				List[Any]					   =			{"pixel_values": pixel_values}
							return config, inputs_dict






@require_torch
class 			SCREAMING_SNAKE_CASE__	(					lowerCamelCase__				,lowerCamelCase__				,unittest.TestCase						):







					"""simple docstring"""






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

					SCREAMING_SNAKE_CASE				=     False
					SCREAMING_SNAKE_CASE				=     False
					SCREAMING_SNAKE_CASE				=     False
					SCREAMING_SNAKE_CASE				=     False
					SCREAMING_SNAKE_CASE				=     False
					def 						lowerCamelCase_					(					self    :	str						):







							"""simple docstring"""
							__UpperCAmelCase     :				Union[str, Any]					   =			EfficientNetModelTester(self						)
							__UpperCAmelCase     :				Any					   =			ConfigTester(
							    self						,     config_class=_UpperCAmelCase						,     has_text_modality=_UpperCAmelCase						,     hidden_size=37						)
					def 						lowerCamelCase_					(					self    :	List[Any]						):







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







							"""simple docstring"""
							return
					@unittest.skip(reason="EfficientNet does not use inputs_embeds"						)
					def 						lowerCamelCase_					(					self    :	Optional[Any]						):







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







							"""simple docstring"""
							pass
					@unittest.skip(reason="EfficientNet does not use feedforward chunking"						)
					def 						lowerCamelCase_					(					self    :	int						):







							"""simple docstring"""
							pass
					def 						lowerCamelCase_					(					self    :	List[Any]						):







							"""simple docstring"""
							__UpperCAmelCase   ,       __UpperCAmelCase     :				Dict					   =			self.model_tester.prepare_config_and_inputs_for_common()

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

									__UpperCAmelCase     :				Optional[Any]					   =			["pixel_values"]
									self.assertListEqual(arg_names[:1]						,     _UpperCAmelCase						)
					def 						lowerCamelCase_					(					self    :	int						):







							"""simple docstring"""
							__UpperCAmelCase     :				Tuple					   =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_UpperCAmelCase						)
					def 						lowerCamelCase_					(					self    :	Union[str, Any]						):







							"""simple docstring"""
							def check_hidden_states_output(UpperCAmelCase_    :	Union[str, Any]						,     UpperCAmelCase_    :	str						,     UpperCAmelCase_    :	List[str]						):
									__UpperCAmelCase     :				Optional[int]					   =			model_class(_UpperCAmelCase						)
									model.to(_UpperCAmelCase						)
									model.eval()

									with torch.no_grad():
											__UpperCAmelCase     :				Optional[Any]					   =			model(**self._prepare_for_class(_UpperCAmelCase						,     _UpperCAmelCase						)						)

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

							__UpperCAmelCase   ,       __UpperCAmelCase     :				int					   =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									__UpperCAmelCase     :				Tuple					   =			True
									check_hidden_states_output(_UpperCAmelCase						,     _UpperCAmelCase						,     _UpperCAmelCase						)

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

									check_hidden_states_output(_UpperCAmelCase						,     _UpperCAmelCase						,     _UpperCAmelCase						)
					def 						lowerCamelCase_					(					self    :	List[Any]						):







							"""simple docstring"""
							__UpperCAmelCase     :				List[str]					   =			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 						lowerCamelCase_					(					self    :	List[Any]						):







							"""simple docstring"""
							pass
					@slow
					def 						lowerCamelCase_					(					self    :	Tuple						):







							"""simple docstring"""
							for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__UpperCAmelCase     :				Any					   =			EfficientNetModel.from_pretrained(_UpperCAmelCase						)
									self.assertIsNotNone(_UpperCAmelCase						)






					@is_pipeline_test
					@require_vision
					@slow
					def 						lowerCamelCase_					(					self    :	Union[str, Any]						):







							"""simple docstring"""
							super().test_pipeline_image_classification()






def 		__UpperCamelCase		(       ):
		__UpperCAmelCase     :				List[str]					   =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
		return image






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







					"""simple docstring"""






					@cached_property
					def 						lowerCamelCase_					(					self    :	Optional[Any]						):







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






					@slow
					def 						lowerCamelCase_					(					self    :	Optional[Any]						):







							"""simple docstring"""
							__UpperCAmelCase     :				Any					   =			EfficientNetForImageClassification.from_pretrained("google/efficientnet-b7"						).to(_UpperCAmelCase						)

							__UpperCAmelCase     :				Optional[Any]					   =			self.default_image_processor
							__UpperCAmelCase     :				List[str]					   =			prepare_img()
							__UpperCAmelCase     :				Optional[Any]					   =			image_processor(images=_UpperCAmelCase						,     return_tensors="pt"						).to(_UpperCAmelCase						)

							# forward pass
							with torch.no_grad():
									__UpperCAmelCase     :				Union[str, Any]					   =			model(**_UpperCAmelCase						)

							# verify the logits
							__UpperCAmelCase     :				Optional[Any]					   =			torch.Size((1, 1_000)						)
							self.assertEqual(outputs.logits.shape						,     _UpperCAmelCase						)

							__UpperCAmelCase     :				List[Any]					   =			torch.tensor([0.0001, 0.0002, 0.0002]						).to(_UpperCAmelCase						)
							self.assertTrue(torch.allclose(outputs.logits[0, :3]						,     _UpperCAmelCase						,     atol=1e-4						)						)








import argparse
import json
import re
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    MobileNetVaConfig,
    MobileNetVaForImageClassification,
    MobileNetVaForSemanticSegmentation,
    MobileNetVaImageProcessor,
    load_tf_weights_in_mobilenet_va,
)
from transformers.utils import logging


logging.set_verbosity_info()
UpperCAmelCase			=    logging.get_logger(__name__)






def        __lowerCAmelCase    (SCREAMING_SNAKE_CASE					)->  Any:




      """simple docstring"""

      snake_case_       =      MobileNetVaConfig(layer_norm_eps=0.0_0_1					)

      if "quant" in model_name:
            raise ValueError('''Quantized models are not supported.'''					)

      snake_case_       =      re.match(R'''^.*mobilenet_v2_([^_]*)_([^_]*)$'''					,					SCREAMING_SNAKE_CASE					)
      if matches:
            snake_case_       =      float(matches[1]					)
            snake_case_       =      int(matches[2]					)

      if model_name.startswith('''deeplabv3_'''					):
            snake_case_       =      8
            snake_case_       =      21
            snake_case_       =      '''pascal-voc-id2label.json'''
      else:
            # The TensorFlow version of MobileNetV2 predicts 1001 classes instead
            # of the usual 1000. The first class (index 0) is "background".
            snake_case_       =      1001
            snake_case_       =      '''imagenet-1k-id2label.json'''

      snake_case_       =      '''huggingface/label-files'''
      snake_case_       =      json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE					,					repo_type='''dataset'''					)					,					'''r'''					)					)

      if config.num_labels == 1001:
            snake_case_       =      {int(SCREAMING_SNAKE_CASE					) + 1: v for k, v in idalabel.items()}
            snake_case_       =      '''background'''
      else:
            snake_case_       =      {int(SCREAMING_SNAKE_CASE					): v for k, v in idalabel.items()}

      snake_case_       =      idalabel
      snake_case_       =      {v: k for k, v in idalabel.items()}

      return config






def        __lowerCAmelCase    ()->  str:




      """simple docstring"""

      snake_case_       =      '''http://images.cocodataset.org/val2017/000000039769.jpg'''
      snake_case_       =      Image.open(requests.get(SCREAMING_SNAKE_CASE					,					stream=SCREAMING_SNAKE_CASE					).raw					)
      return im






@torch.no_grad()
def        __lowerCAmelCase    (SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE=False					)->  str:




      """simple docstring"""

      snake_case_       =      get_mobilenet_va_config(SCREAMING_SNAKE_CASE					)

      # Load 🤗 model
      if model_name.startswith('''deeplabv3_'''					):
            snake_case_       =      MobileNetVaForSemanticSegmentation(SCREAMING_SNAKE_CASE					).eval()
      else:
            snake_case_       =      MobileNetVaForImageClassification(SCREAMING_SNAKE_CASE					).eval()

      # Load weights from TensorFlow checkpoint
      load_tf_weights_in_mobilenet_va(SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE					)

      # Check outputs on an image, prepared by MobileNetV2ImageProcessor
      snake_case_       =      MobileNetVaImageProcessor(
          crop_size={'''width''': config.image_size, '''height''': config.image_size}					,					size={'''shortest_edge''': config.image_size + 32}					,					)
      snake_case_       =      image_processor(images=prepare_img()					,					return_tensors='''pt'''					)
      snake_case_       =      model(**SCREAMING_SNAKE_CASE					)
      snake_case_       =      outputs.logits

      if model_name.startswith('''deeplabv3_'''					):
            assert logits.shape == (1, 21, 65, 65)

            if model_name == "deeplabv3_mobilenet_v2_1.0_513":
                  snake_case_       =      torch.tensor(
                      [
                          [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]],
                          [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]],
                          [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]],
                      ]					)

            else:
                  raise ValueError(f'''Unknown model name: {model_name}'''					)

            assert torch.allclose(logits[0, :3, :3, :3]					,					SCREAMING_SNAKE_CASE					,					atol=1E-4					)
      else:
            assert logits.shape == (1, 1001)

            if model_name == "mobilenet_v2_1.4_224":
                  snake_case_       =      torch.tensor([0.0_1_8_1, -1.0_0_1_5, 0.4_6_8_8]					)
            elif model_name == "mobilenet_v2_1.0_224":
                  snake_case_       =      torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5]					)
            elif model_name == "mobilenet_v2_0.75_160":
                  snake_case_       =      torch.tensor([0.2_4_8_2, 0.4_1_3_6, 0.6_6_6_9]					)
            elif model_name == "mobilenet_v2_0.35_96":
                  snake_case_       =      torch.tensor([0.1_4_5_1, -0.4_6_2_4, 0.7_1_9_2]					)
            else:
                  snake_case_       =      None

            if expected_logits is not None:
                  assert torch.allclose(logits[0, :3]					,					SCREAMING_SNAKE_CASE					,					atol=1E-4					)

      Path(SCREAMING_SNAKE_CASE					).mkdir(exist_ok=SCREAMING_SNAKE_CASE					)
      print(f'''Saving model {model_name} to {pytorch_dump_folder_path}'''					)
      model.save_pretrained(SCREAMING_SNAKE_CASE					)
      print(f'''Saving image processor to {pytorch_dump_folder_path}'''					)
      image_processor.save_pretrained(SCREAMING_SNAKE_CASE					)

      if push_to_hub:
            print('''Pushing to the hub...'''					)
            snake_case_       =      '''google/''' + model_name
            image_processor.push_to_hub(SCREAMING_SNAKE_CASE					)
            model.push_to_hub(SCREAMING_SNAKE_CASE					)


if __name__ == "__main__":
   UpperCAmelCase			=    argparse.ArgumentParser()
   # Required parameters
   parser.add_argument(
       """--model_name""",
       default="""mobilenet_v2_1.0_224""",
       type=str,
       help="""Name of the MobileNetV2 model you'd like to convert. Should in the form 'mobilenet_v2_<depth>_<size>'.""",
   )
   parser.add_argument(
       """--checkpoint_path""", required=True, type=str, help="""Path to the original TensorFlow checkpoint (.ckpt file)."""
   )
   parser.add_argument(
       """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory."""
   )
   parser.add_argument(
       """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
   )

   UpperCAmelCase			=    parser.parse_args()
   convert_movilevit_checkpoint(
       args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
   )