



'''simple docstring'''



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 _UpperCamelCase		(     A		):





				'''simple docstring'''





				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											__lowercase       	=self.config_class(**self.inputs_dict)
											self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE  ,       'tf_padding'))
											self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE  ,       'depth_multiplier'))





class _UpperCamelCase		:





				'''simple docstring'''





				def __init__(							self  :  Tuple  ,       _lowerCAmelCase  :  Any  ,       _lowerCAmelCase  :  Optional[Any]=1_3  ,       _lowerCAmelCase  :  Tuple=3  ,       _lowerCAmelCase  :  int=3_2  ,       _lowerCAmelCase  :  Optional[int]=0.25  ,       _lowerCAmelCase  :  List[Any]=8  ,       _lowerCAmelCase  :  Tuple=True  ,       _lowerCAmelCase  :  Optional[int]=1_0_2_4  ,       _lowerCAmelCase  :  int=3_2  ,       _lowerCAmelCase  :  Tuple="relu6"  ,       _lowerCAmelCase  :  Optional[int]=0.1  ,       _lowerCAmelCase  :  Union[str, Any]=0.02  ,       _lowerCAmelCase  :  Optional[int]=True  ,       _lowerCAmelCase  :  Dict=True  ,       _lowerCAmelCase  :  Optional[Any]=1_0  ,       _lowerCAmelCase  :  Optional[Any]=None  ,       ):







											'''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 				__lowerCamelCase     (							self  :  List[Any]):







											'''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 				__lowerCamelCase     (							self  :  Optional[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 				__lowerCamelCase     (							self  :  List[str]  ,       _lowerCAmelCase  :  Tuple  ,       _lowerCAmelCase  :  Union[str, Any]  ,       _lowerCAmelCase  :  Optional[int]  ,       _lowerCAmelCase  :  Tuple):







											'''simple docstring'''

											__lowercase       	=MobileNetVaModel(config=_SCREAMING_SNAKE_CASE)
											model.to(_SCREAMING_SNAKE_CASE)
											model.eval()
											__lowercase       	=model(_SCREAMING_SNAKE_CASE)
											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 				__lowerCamelCase     (							self  :  Any  ,       _lowerCAmelCase  :  List[Any]  ,       _lowerCAmelCase  :  Dict  ,       _lowerCAmelCase  :  str  ,       _lowerCAmelCase  :  Any):







											'''simple docstring'''

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

				def 				__lowerCamelCase     (							self  :  Optional[int]):







											'''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 _UpperCamelCase		(     A      ,       A      ,       unittest.TestCase		):





				'''simple docstring'''





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

				lowerCAmelCase__					    =    False
				lowerCAmelCase__					    =    False
				lowerCAmelCase__					    =    False
				lowerCAmelCase__					    =    False

				def 				__lowerCamelCase     (							self  :  Optional[Any]):







											'''simple docstring'''

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

				def 				__lowerCamelCase     (							self  :  Dict):







											'''simple docstring'''

											self.config_tester.run_common_tests()

				@unittest.skip(reason='MobileNetV1 does not use inputs_embeds')
				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											pass

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







											'''simple docstring'''

											pass

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







											'''simple docstring'''

											pass

				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											__lowercase	,				__lowercase       	=self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		__lowercase       	=model_class(_SCREAMING_SNAKE_CASE)
																		__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]  ,       _SCREAMING_SNAKE_CASE)

				def 				__lowerCamelCase     (							self  :  Tuple):







											'''simple docstring'''

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

				def 				__lowerCamelCase     (							self  :  str):







											'''simple docstring'''

											def check_hidden_states_output(_lowerCAmelCase  :  Any  ,       _lowerCAmelCase  :  Any  ,       _lowerCAmelCase  :  Any):
																		__lowercase       	=model_class(_SCREAMING_SNAKE_CASE)
																		model.to(_SCREAMING_SNAKE_CASE)
																		model.eval()

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

																		__lowercase       	=outputs.hidden_states

																		__lowercase       	=2_6
																		self.assertEqual(len(_SCREAMING_SNAKE_CASE)  ,       _SCREAMING_SNAKE_CASE)

											__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(_SCREAMING_SNAKE_CASE  ,       _SCREAMING_SNAKE_CASE  ,       _SCREAMING_SNAKE_CASE)

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

																		check_hidden_states_output(_SCREAMING_SNAKE_CASE  ,       _SCREAMING_SNAKE_CASE  ,       _SCREAMING_SNAKE_CASE)

				def 				__lowerCamelCase     (							self  :  Any):







											'''simple docstring'''

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

				@slow
				def 				__lowerCamelCase     (							self  :  Tuple):







											'''simple docstring'''

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



def   _A       (   ):



							"""simple docstring"""



							__lowercase       	=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
							return image





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





				'''simple docstring'''





				@cached_property
				def 				__lowerCamelCase     (							self  :  Tuple):







											'''simple docstring'''

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

				@slow
				def 				__lowerCamelCase     (							self  :  str):







											'''simple docstring'''

											__lowercase       	=MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224').to(_SCREAMING_SNAKE_CASE)

											__lowercase       	=self.default_image_processor
											__lowercase       	=prepare_img()
											__lowercase       	=image_processor(images=_SCREAMING_SNAKE_CASE  ,       return_tensors='pt').to(_SCREAMING_SNAKE_CASE)

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

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

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

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








'''simple docstring'''



def   _A       (   _lowerCAmelCase					):



							"""simple docstring"""



							if not isinstance(_lowerCAmelCase  ,   _lowerCAmelCase					):
														raise TypeError('only integers accepted as input'					)
							else:
														__lowercase       	=str(abs(_lowerCAmelCase					)					)
														__lowercase       	=[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()



