






import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import 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 MobileNetVaForImageClassification, MobileNetVaModel
			from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import MobileNetVaImageProcessor
class 			_lowerCAmelCase   ( _UpperCAmelCase			):






			"""simple docstring"""





			def 		snake_case__			(				self	:       Any   )						->					Optional[Any]:
									"""simple docstring"""







									__lowercase					=				self.config_class(**self.inputs_dict   )
									self.parent.assertTrue(hasattr(lowercase			,     """tf_padding"""   )   )
									self.parent.assertTrue(hasattr(lowercase			,     """depth_multiplier"""   )   )





class 			_lowerCAmelCase   :






			"""simple docstring"""





			def __init__(				self	:       List[Any]			,     lowercase	:       Optional[int]			,     lowercase	:       Union[str, Any]=13			,     lowercase	:       Any=3			,     lowercase	:       Any=32			,     lowercase	:       int=0.25			,     lowercase	:       Dict=8			,     lowercase	:       Dict=True			,     lowercase	:       Dict=1_024			,     lowercase	:       Dict=32			,     lowercase	:       Tuple="relu6"			,     lowercase	:       Optional[Any]=0.1			,     lowercase	:       Any=0.02			,     lowercase	:       str=True			,     lowercase	:       List[Any]=True			,     lowercase	:       List[str]=10			,     lowercase	:       List[Any]=None			,     )						->					List[Any]:
									"""simple docstring"""







									__lowercase					=				parent
									__lowercase					=				batch_size
									__lowercase					=				num_channels
									__lowercase					=				image_size
									__lowercase					=				depth_multiplier
									__lowercase					=				min_depth
									__lowercase					=				tf_padding
									__lowercase					=				int(last_hidden_size * depth_multiplier   )
									__lowercase					=				output_stride
									__lowercase					=				hidden_act
									__lowercase					=				classifier_dropout_prob
									__lowercase					=				use_labels
									__lowercase					=				is_training
									__lowercase					=				num_labels
									__lowercase					=				initializer_range
									__lowercase					=				scope





			def 		snake_case__			(				self	:       str   )						->					str:
									"""simple docstring"""







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

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

									__lowercase					=				self.get_config()

									return config, pixel_values, labels, pixel_labels





			def 		snake_case__			(				self	:       List[Any]   )						->					List[Any]:
									"""simple docstring"""







									return MobileNetVaConfig(
									    num_channels=self.num_channels			,     image_size=self.image_size			,     depth_multiplier=self.depth_multiplier			,     min_depth=self.min_depth			,     tf_padding=self.tf_padding			,     hidden_act=self.hidden_act			,     classifier_dropout_prob=self.classifier_dropout_prob			,     initializer_range=self.initializer_range			,     )





			def 		snake_case__			(				self	:       List[str]			,     lowercase	:       Optional[Any]			,     lowercase	:       Dict			,     lowercase	:       Optional[int]			,     lowercase	:       List[str]   )						->					Any:
									"""simple docstring"""







									__lowercase					=				MobileNetVaModel(config=lowercase   )
									model.to(lowercase   )
									model.eval()
									__lowercase					=				model(lowercase   )
									self.parent.assertEqual(
									    result.last_hidden_state.shape			,     (
									        self.batch_size,
									        self.last_hidden_size,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    )			,     )





			def 		snake_case__			(				self	:       Tuple			,     lowercase	:       str			,     lowercase	:       str			,     lowercase	:       str			,     lowercase	:       Union[str, Any]   )						->					List[str]:
									"""simple docstring"""







									__lowercase					=				self.num_labels
									__lowercase					=				MobileNetVaForImageClassification(lowercase   )
									model.to(lowercase   )
									model.eval()
									__lowercase					=				model(lowercase			,     labels=lowercase   )
									self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.num_labels)   )







			def 		snake_case__			(				self	:       Any   )						->					Tuple:
									"""simple docstring"""







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





@require_torch
class 			_lowerCAmelCase   ( _UpperCAmelCase    ,					_UpperCAmelCase    ,					unittest.TestCase			):






			"""simple docstring"""





			lowercase__      :  Optional[int]      =			(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
			lowercase__      :  Tuple      =			(
			    {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
			    if is_torch_available()
			    else {}
			)

			lowercase__      :  str      =			False
			lowercase__      :  int      =			False
			lowercase__      :  Any      =			False
			lowercase__      :  Tuple      =			False





			def 		snake_case__			(				self	:       Any   )						->					Dict:
									"""simple docstring"""







									__lowercase					=				MobileNetVaModelTester(self   )
									__lowercase					=				MobileNetVaConfigTester(self			,     config_class=lowercase			,     has_text_modality=lowercase   )





			def 		snake_case__			(				self	:       List[str]   )						->					str:
									"""simple docstring"""







									self.config_tester.run_common_tests()





			@unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""   )
			def 		snake_case__			(				self	:       Tuple   )						->					List[Any]:
									"""simple docstring"""







									pass





			@unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""   )
			def 		snake_case__			(				self	:       List[str]   )						->					Tuple:
									"""simple docstring"""







									pass





			@unittest.skip(reason="""MobileNetV1 does not output attentions"""   )
			def 		snake_case__			(				self	:       Tuple   )						->					int:
									"""simple docstring"""







									pass





			def 		snake_case__			(				self	:       Tuple   )						->					Dict:
									"""simple docstring"""







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()

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

															__lowercase					=				["""pixel_values"""]
															self.assertListEqual(arg_names[:1]			,     lowercase   )





			def 		snake_case__			(				self	:       str   )						->					Optional[Any]:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowercase   )





			def 		snake_case__			(				self	:       int   )						->					Dict:
									"""simple docstring"""







									def check_hidden_states_output(lowercase	:       List[Any]			,     lowercase	:       Tuple			,     lowercase	:       Union[str, Any]   ):
															__lowercase					=				model_class(lowercase   )
															model.to(lowercase   )
															model.eval()

															with torch.no_grad():
																					__lowercase					=				model(**self._prepare_for_class(lowercase			,     lowercase   )   )

															__lowercase					=				outputs.hidden_states

															__lowercase					=				26
															self.assertEqual(len(lowercase   )			,     lowercase   )

									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															__lowercase					=				True
															check_hidden_states_output(lowercase			,     lowercase			,     lowercase   )

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

															check_hidden_states_output(lowercase			,     lowercase			,     lowercase   )





			def 		snake_case__			(				self	:       Dict   )						->					List[Any]:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowercase   )







			@slow
			def 		snake_case__			(				self	:       Dict   )						->					Dict:
									"""simple docstring"""







									for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															__lowercase					=				MobileNetVaModel.from_pretrained(lowercase   )
															self.assertIsNotNone(lowercase   )






def  UpperCAmelCase__    (    ) ->      Union[str, Any]:
						__lowercase					=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
						return image







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






			"""simple docstring"""





			@cached_property
			def 		snake_case__			(				self	:       List[str]   )						->					Dict:
									"""simple docstring"""







									return (
									    MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224"""   ) if is_vision_available() else None
									)







			@slow
			def 		snake_case__			(				self	:       Union[str, Any]   )						->					str:
									"""simple docstring"""







									__lowercase					=				MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""   ).to(lowercase   )

									__lowercase					=				self.default_image_processor
									__lowercase					=				prepare_img()
									__lowercase					=				image_processor(images=lowercase			,     return_tensors="""pt"""   ).to(lowercase   )

									# forward pass
									with torch.no_grad():
															__lowercase					=				model(**lowercase   )

									# verify the logits
									__lowercase					=				torch.Size((1, 1_001)   )
									self.assertEqual(outputs.logits.shape			,     lowercase   )

									__lowercase					=				torch.tensor([-4.1739, -1.1233, 3.1205]   ).to(lowercase   )

									self.assertTrue(torch.allclose(outputs.logits[0, :3]			,     lowercase			,     atol=1E-4   )   )










UpperCamelCase__ =						{
    "joule": 1.0,
    "kilojoule": 10_00,
    "megajoule": 1_00_00_00,
    "gigajoule": 10_00_00_00_00,
    "wattsecond": 1.0,
    "watthour": 36_00,
    "kilowatthour": 3_60_00_00,
    "newtonmeter": 1.0,
    "calorie_nutr": 41_86.8,
    "kilocalorie_nutr": 4_18_68_00.00,
    "electronvolt": 1.6_0217_6634e-19,
    "britishthermalunit_it": 10_55.0_55_85,
    "footpound": 1.355_818,
}






def  UpperCAmelCase__    (    lowercase__						,       lowercase__						,       lowercase__   ) ->      float:
						if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION:
												__lowercase					=				(
												    F"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"
												    F"Valid values are: {', '.join(lowercase__   )}"
												)
												raise ValueError(lowercase__   )
						return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type]


if __name__ == "__main__":
			import doctest

			doctest.testmod()





