




'''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      lowerCAmelCase (			__lowercase):


       def    lowerCAmelCase   ( self	)   ->	Any:



            '''simple docstring'''




            __snake_case            =	self.config_class(**self.inputs_dict	)
            self.parent.assertTrue(hasattr(_a     ,	'''tf_padding'''	)	)
            self.parent.assertTrue(hasattr(_a     ,	'''depth_multiplier'''	)	)





class      lowerCAmelCase :


       def __init__( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=13     ,	__SCREAMING_SNAKE_CASE=3     ,	__SCREAMING_SNAKE_CASE=32     ,	__SCREAMING_SNAKE_CASE=0.25     ,	__SCREAMING_SNAKE_CASE=8     ,	__SCREAMING_SNAKE_CASE=True     ,	__SCREAMING_SNAKE_CASE=1024     ,	__SCREAMING_SNAKE_CASE=32     ,	__SCREAMING_SNAKE_CASE="relu6"     ,	__SCREAMING_SNAKE_CASE=0.1     ,	__SCREAMING_SNAKE_CASE=0.02     ,	__SCREAMING_SNAKE_CASE=True     ,	__SCREAMING_SNAKE_CASE=True     ,	__SCREAMING_SNAKE_CASE=10     ,	__SCREAMING_SNAKE_CASE=None     ,	)   ->	Any:



            '''simple docstring'''




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


       def    lowerCAmelCase   ( self	)   ->	Optional[int]:



            '''simple docstring'''




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

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

            __snake_case            =	self.get_config()

            return config, pixel_values, labels, pixel_labels


       def    lowerCAmelCase   ( self	)   ->	Union[str, 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     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)   ->	Dict:



            '''simple docstring'''




            __snake_case            =	MobileNetVaModel(config=_a	)
            model.to(_a	)
            model.eval()
            __snake_case            =	model(_a	)
            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     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)   ->	Dict:



            '''simple docstring'''




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




       def    lowerCAmelCase   ( self	)   ->	Dict:



            '''simple docstring'''




            __snake_case            =	self.prepare_config_and_inputs()
            __snake_case            =	config_and_inputs
            __snake_case            =	{'''pixel_values''': pixel_values}
            return config, inputs_dict





@require_torch
class      lowerCAmelCase (			__lowercase					, __lowercase					, unittest.TestCase):
       __lowercase	:   str										=      (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
       __lowercase	:   Union[str, Any]										=      (
           {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification}
           if is_torch_available()
           else {}
       )

       __lowercase	:   Dict										=      False
       __lowercase	:   List[Any]										=      False
       __lowercase	:   Tuple										=      False
       __lowercase	:   str										=      False


       def    lowerCAmelCase   ( self	)   ->	str:



            '''simple docstring'''




            __snake_case            =	MobileNetVaModelTester(self	)
            __snake_case            =	MobileNetVaConfigTester(self     ,	config_class=_a     ,	has_text_modality=_a	)


       def    lowerCAmelCase   ( self	)   ->	str:



            '''simple docstring'''




            self.config_tester.run_common_tests()


       @unittest.skip(reason='''MobileNetV1 does not use inputs_embeds'''	)
       def    lowerCAmelCase   ( self	)   ->	Union[str, Any]:



            '''simple docstring'''




            pass


       @unittest.skip(reason='''MobileNetV1 does not support input and output embeddings'''	)
       def    lowerCAmelCase   ( self	)   ->	int:



            '''simple docstring'''




            pass


       @unittest.skip(reason='''MobileNetV1 does not output attentions'''	)
       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            pass


       def    lowerCAmelCase   ( self	)   ->	List[str]:



            '''simple docstring'''




            __snake_case            =	self.model_tester.prepare_config_and_inputs_for_common()

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

                 __snake_case            =	['''pixel_values''']
                 self.assertListEqual(arg_names[:1]     ,	_a	)


       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            __snake_case            =	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_a	)


       def    lowerCAmelCase   ( self	)   ->	List[Any]:



            '''simple docstring'''




            def check_hidden_states_output(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	):
                 __snake_case            =	model_class(_a	)
                 model.to(_a	)
                 model.eval()

                 with torch.no_grad():
                      __snake_case            =	model(**self._prepare_for_class(_a     ,	_a	)	)

                 __snake_case            =	outputs.hidden_states

                 __snake_case            =	26
                 self.assertEqual(len(_a	)     ,	_a	)

            __snake_case            =	self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 __snake_case            =	True
                 check_hidden_states_output(_a     ,	_a     ,	_a	)

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

                 check_hidden_states_output(_a     ,	_a     ,	_a	)


       def    lowerCAmelCase   ( self	)   ->	List[Any]:



            '''simple docstring'''




            __snake_case            =	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_a	)




       @slow
       def    lowerCAmelCase   ( self	)   ->	str:



            '''simple docstring'''




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







def       _UpperCamelCase			()-> str:




     '''simple docstring'''





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







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


       @cached_property
       def    lowerCAmelCase   ( self	)   ->	List[Any]:



            '''simple docstring'''




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




       @slow
       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            __snake_case            =	MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224'''	).to(_a	)

            __snake_case            =	self.default_image_processor
            __snake_case            =	prepare_img()
            __snake_case            =	image_processor(images=_a     ,	return_tensors='''pt'''	).to(_a	)

            # forward pass
            with torch.no_grad():
                 __snake_case            =	model(**_a	)

            # verify the logits
            __snake_case            =	torch.Size((1, 1001)	)
            self.assertEqual(outputs.logits.shape     ,	_a	)

            __snake_case            =	torch.tensor([-4.1_739, -1.1_233, 3.1_205]	).to(_a	)

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









a__												=						'''Input must be a string of 8 numbers plus letter'''
a__												=						'''TRWAGMYFPDXBNJZSQVHLCKE'''



def   __UpperCAmelCase					(      __a :     str      )     ->	bool:

					"""simple docstring"""

					if not isinstance(__a						,__a      ):
										_a      :       List[str]   =						F"""Expected string as input, found {type(__a      ).__name__}"""
										raise TypeError(__a      )

					_a      :       List[Any]   =						spanish_id.replace('''-'''						,''''''      ).upper()
					if len(__a      ) != 9:
										raise ValueError(__a      )

					try:
										_a      :       Any   =						int(spanish_id_clean[0:8]      )
										_a      :       str   =						spanish_id_clean[8]
					except ValueError as ex:
										raise ValueError(__a      ) from ex

					if letter.isdigit():
										raise ValueError(__a      )

					return letter == LOOKUP_LETTERS[number % 23]


if __name__ == "__main__":
			import doctest

			doctest.testmod()



