





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 			lowercase				(							a_     ):



						"""simple docstring"""

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





										'''simple docstring'''







										_snake_case :			Dict  						=   self.config_class(**self.inputs_dict					)
										self.parent.assertTrue(hasattr(lowerCamelCase_ ,				'tf_padding'					)					)
										self.parent.assertTrue(hasattr(lowerCamelCase_ ,				'depth_multiplier'					)					)



class 			lowercase				:



						"""simple docstring"""

						def __init__(    self			:		Optional[Any] ,				lowerCamelCase_			:		int ,				lowerCamelCase_			:		List[str]=13 ,				lowerCamelCase_			:		Tuple=3 ,				lowerCamelCase_			:		List[str]=32 ,				lowerCamelCase_			:		Optional[Any]=0.25 ,				lowerCamelCase_			:		str=8 ,				lowerCamelCase_			:		Union[str, Any]=True ,				lowerCamelCase_			:		int=10_24 ,				lowerCamelCase_			:		Optional[Any]=32 ,				lowerCamelCase_			:		str="relu6" ,				lowerCamelCase_			:		Tuple=0.1 ,				lowerCamelCase_			:		Union[str, Any]=0.02 ,				lowerCamelCase_			:		Optional[int]=True ,				lowerCamelCase_			:		int=True ,				lowerCamelCase_			:		Dict=10 ,				lowerCamelCase_			:		str=None ,				):





										'''simple docstring'''







										_snake_case :			List[Any]  						=   parent
										_snake_case :			int  						=   batch_size
										_snake_case :			Optional[Any]  						=   num_channels
										_snake_case :			Optional[Any]  						=   image_size
										_snake_case :			Optional[Any]  						=   depth_multiplier
										_snake_case :			Tuple  						=   min_depth
										_snake_case :			Any  						=   tf_padding
										_snake_case :			Optional[Any]  						=   int(last_hidden_size * depth_multiplier					)
										_snake_case :			Any  						=   output_stride
										_snake_case :			str  						=   hidden_act
										_snake_case :			Dict  						=   classifier_dropout_prob
										_snake_case :			Union[str, Any]  						=   use_labels
										_snake_case :			Dict  						=   is_training
										_snake_case :			str  						=   num_labels
										_snake_case :			Union[str, Any]  						=   initializer_range
										_snake_case :			Optional[int]  						=   scope







						def 		__UpperCAmelCase       (    self			:		List[str]					):





										'''simple docstring'''







										_snake_case :			str  						=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

										_snake_case :			Optional[Any]  						=   None
										_snake_case :			Dict  						=   None
										if self.use_labels:
														_snake_case :			List[str]  						=   ids_tensor([self.batch_size] ,				self.num_labels					)
														_snake_case :			Any  						=   ids_tensor([self.batch_size, self.image_size, self.image_size] ,				self.num_labels					)

										_snake_case :			Any  						=   self.get_config()

										return config, pixel_values, labels, pixel_labels







						def 		__UpperCAmelCase       (    self			:		str					):





										'''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 		__UpperCAmelCase       (    self			:		List[Any] ,				lowerCamelCase_			:		Dict ,				lowerCamelCase_			:		str ,				lowerCamelCase_			:		Dict ,				lowerCamelCase_			:		Optional[int]					):





										'''simple docstring'''







										_snake_case :			List[Any]  						=   MobileNetVaModel(config=lowerCamelCase_					)
										model.to(lowerCamelCase_					)
										model.eval()
										_snake_case :			List[Any]  						=   model(lowerCamelCase_					)
										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 		__UpperCAmelCase       (    self			:		Dict ,				lowerCamelCase_			:		Union[str, Any] ,				lowerCamelCase_			:		List[str] ,				lowerCamelCase_			:		int ,				lowerCamelCase_			:		List[str]					):





										'''simple docstring'''







										_snake_case :			List[Any]  						=   self.num_labels
										_snake_case :			Tuple  						=   MobileNetVaForImageClassification(lowerCamelCase_					)
										model.to(lowerCamelCase_					)
										model.eval()
										_snake_case :			Tuple  						=   model(lowerCamelCase_ ,				labels=lowerCamelCase_					)
										self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)					)







						def 		__UpperCAmelCase       (    self			:		int					):





										'''simple docstring'''







										_snake_case :			Optional[int]  						=   self.prepare_config_and_inputs()
										_snake_case :			Dict  						=   config_and_inputs
										_snake_case :			List[Any]  						=   {'pixel_values': pixel_values}
										return config, inputs_dict



@require_torch
class 			lowercase				(							a_		,			a_		,			unittest.TestCase     ):



						"""simple docstring"""

						_UpperCamelCase  :	int								=	(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
						_UpperCamelCase  :	str								=	(
						    {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification}
						    if is_torch_available()
						    else {}
						)

						_UpperCamelCase  :	Optional[int]								=	False
						_UpperCamelCase  :	Tuple								=	False
						_UpperCamelCase  :	Optional[Any]								=	False
						_UpperCamelCase  :	Tuple								=	False







						def 		__UpperCAmelCase       (    self			:		List[Any]					):





										'''simple docstring'''







										_snake_case :			int  						=   MobileNetVaModelTester(self					)
										_snake_case :			str  						=   MobileNetVaConfigTester(self ,				config_class=lowerCamelCase_ ,				has_text_modality=lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		Optional[Any]					):





										'''simple docstring'''







										self.config_tester.run_common_tests()







						@unittest.skip(reason='MobileNetV1 does not use inputs_embeds'					)
						def 		__UpperCAmelCase       (    self			:		Any					):





										'''simple docstring'''







										pass







						@unittest.skip(reason='MobileNetV1 does not support input and output embeddings'					)
						def 		__UpperCAmelCase       (    self			:		Optional[int]					):





										'''simple docstring'''







										pass







						@unittest.skip(reason='MobileNetV1 does not output attentions'					)
						def 		__UpperCAmelCase       (    self			:		Dict					):





										'''simple docstring'''







										pass







						def 		__UpperCAmelCase       (    self			:		str					):





										'''simple docstring'''







										_snake_case :			Tuple  						=   self.model_tester.prepare_config_and_inputs_for_common()

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

														_snake_case :			Optional[Any]  						=   ['pixel_values']
														self.assertListEqual(arg_names[:1] ,				lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		str					):





										'''simple docstring'''







										_snake_case :			Union[str, Any]  						=   self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCamelCase_					)







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





										'''simple docstring'''







										def check_hidden_states_output(lowerCamelCase_			:		Optional[Any] ,				lowerCamelCase_			:		int ,				lowerCamelCase_			:		List[str]					):
														_snake_case :			Dict  						=   model_class(lowerCamelCase_					)
														model.to(lowerCamelCase_					)
														model.eval()

														with torch.no_grad():
																		_snake_case :			List[str]  						=   model(**self._prepare_for_class(lowerCamelCase_ ,				lowerCamelCase_					)					)

														_snake_case :			str  						=   outputs.hidden_states

														_snake_case :			Tuple  						=   26
														self.assertEqual(len(lowerCamelCase_					) ,				lowerCamelCase_					)

										_snake_case :			Dict  						=   self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_snake_case :			Tuple  						=   True
														check_hidden_states_output(lowerCamelCase_ ,				lowerCamelCase_ ,				lowerCamelCase_					)

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														_snake_case :			List[str]  						=   True

														check_hidden_states_output(lowerCamelCase_ ,				lowerCamelCase_ ,				lowerCamelCase_					)







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





										'''simple docstring'''







										_snake_case :			List[str]  						=   self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_					)







						@slow
						def 		__UpperCAmelCase       (    self			:		int					):





										'''simple docstring'''







										for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														_snake_case :			Dict  						=   MobileNetVaModel.from_pretrained(lowerCamelCase_					)
														self.assertIsNotNone(lowerCamelCase_					)



def       A__(		):
				_snake_case :			Optional[int]  						=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
				return image


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



						"""simple docstring"""

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





										'''simple docstring'''







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







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





										'''simple docstring'''







										_snake_case :			int  						=   MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'					).to(lowerCamelCase_					)

										_snake_case :			List[str]  						=   self.default_image_processor
										_snake_case :			Optional[int]  						=   prepare_img()
										_snake_case :			Optional[Any]  						=   image_processor(images=lowerCamelCase_ ,				return_tensors='pt'					).to(lowerCamelCase_					)

										# forward pass
										with torch.no_grad():
														_snake_case :			Optional[int]  						=   model(**lowerCamelCase_					)

										# verify the logits
										_snake_case :			Any  						=   torch.Size((1, 10_01)					)
										self.assertEqual(outputs.logits.shape ,				lowerCamelCase_					)

										_snake_case :			List[str]  						=   torch.tensor([-4.1739, -1.1233, 3.1205]					).to(lowerCamelCase_					)

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













def       A__(		__lowerCAmelCase ):

				if not isinstance(__lowerCAmelCase	,			__lowerCAmelCase ):
								raise TypeError('only integers accepted as input' )
				else:
								_snake_case :			Any  						=   str(abs(__lowerCAmelCase ) )
								_snake_case :			List[str]  						=   [list(__lowerCAmelCase ) for char in range(len(__lowerCAmelCase ) )]
								for index in range(len(__lowerCAmelCase ) ):
												num_transpositions[index].pop(__lowerCAmelCase )
								return max(
								    int(''.join(list(__lowerCAmelCase ) ) ) for transposition in num_transpositions )


if __name__ == "__main__":
		__import__('''doctest''').testmod()






