





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, MobileNetVaForSemanticSegmentation, MobileNetVaModel
 from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import MobileNetVaImageProcessor


class     __magic_name__     (							__SCREAMING_SNAKE_CASE							):





     """simple docstring"""



     def   SCREAMING_SNAKE_CASE						(							self				:str     ):





        '''simple docstring'''




        A_    : Union[str, Any]								=	self.config_class(**self.inputs_dict     )
        self.parent.assertTrue(hasattr(_a	,					"tf_padding"     )     )
        self.parent.assertTrue(hasattr(_a	,					"depth_multiplier"     )     )




class     __magic_name__     :





     """simple docstring"""



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





        '''simple docstring'''




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



     def   SCREAMING_SNAKE_CASE						(							self				:str     ):





        '''simple docstring'''




        A_    : Union[str, Any]								=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

        A_    : int								=	self.get_config()

        return config, pixel_values, labels, pixel_labels



     def   SCREAMING_SNAKE_CASE						(							self				:Dict     ):





        '''simple docstring'''




        return MobileNetVaConfig(
            num_channels=self.num_channels	,					image_size=self.image_size	,					depth_multiplier=self.depth_multiplier	,					depth_divisible_by=self.depth_divisible_by	,					min_depth=self.min_depth	,					expand_ratio=self.expand_ratio	,					output_stride=self.output_stride	,					first_layer_is_expansion=self.first_layer_is_expansion	,					finegrained_output=self.finegrained_output	,					hidden_act=self.hidden_act	,					tf_padding=self.tf_padding	,					classifier_dropout_prob=self.classifier_dropout_prob	,					initializer_range=self.initializer_range	,					)



     def   SCREAMING_SNAKE_CASE						(							self				:Union[str, Any]	,					snake_case				:Optional[int]	,					snake_case				:str	,					snake_case				:Dict	,					snake_case				:Dict     ):





        '''simple docstring'''




        A_    : List[Any]								=	MobileNetVaModel(config=_a     )
        model.to(_a     )
        model.eval()
        A_    : Optional[int]								=	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,
            )	,					)
        self.parent.assertEqual(
            result.pooler_output.shape	,					(self.batch_size, self.last_hidden_size)	,					)



     def   SCREAMING_SNAKE_CASE						(							self				:str	,					snake_case				:Optional[Any]	,					snake_case				:Any	,					snake_case				:str	,					snake_case				:Optional[Any]     ):





        '''simple docstring'''




        A_    : Union[str, Any]								=	self.num_labels
        A_    : Union[str, Any]								=	MobileNetVaForImageClassification(_a     )
        model.to(_a     )
        model.eval()
        A_    : str								=	model(_a	,					labels=_a     )
        self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_labels)     )



     def   SCREAMING_SNAKE_CASE						(							self				:Any	,					snake_case				:Tuple	,					snake_case				:str	,					snake_case				:Union[str, Any]	,					snake_case				:Optional[Any]     ):





        '''simple docstring'''




        A_    : Optional[Any]								=	self.num_labels
        A_    : List[Any]								=	MobileNetVaForSemanticSegmentation(_a     )
        model.to(_a     )
        model.eval()
        A_    : List[str]								=	model(_a     )
        self.parent.assertEqual(
            result.logits.shape	,					(
                self.batch_size,
                self.num_labels,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )	,					)
        A_    : Any								=	model(_a	,					labels=_a     )
        self.parent.assertEqual(
            result.logits.shape	,					(
                self.batch_size,
                self.num_labels,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )	,					)





     def   SCREAMING_SNAKE_CASE						(							self				:str     ):





        '''simple docstring'''




        A_    : List[str]								=	self.prepare_config_and_inputs()
        A_					,  A_					,  A_					,  A_    : int								=	config_and_inputs
        A_    : Union[str, Any]								=	{"pixel_values": pixel_values}
        return config, inputs_dict




@require_torch
class     __magic_name__     (							__SCREAMING_SNAKE_CASE			, __SCREAMING_SNAKE_CASE			, unittest.TestCase							):





     """simple docstring"""



     __UpperCamelCase    			=   (
         (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     __UpperCamelCase    			=   (
         {
             'feature-extraction': MobileNetVaModel,
             'image-classification': MobileNetVaForImageClassification,
             'image-segmentation': MobileNetVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     __UpperCamelCase    			=   False
     __UpperCamelCase    			=   False
     __UpperCamelCase    			=   False
     __UpperCamelCase    			=   False



     def   SCREAMING_SNAKE_CASE						(							self				:List[str]     ):





        '''simple docstring'''




        A_    : Optional[Any]								=	MobileNetVaModelTester(self     )
        A_    : Optional[int]								=	MobileNetVaConfigTester(self	,					config_class=_a	,					has_text_modality=_a     )



     def   SCREAMING_SNAKE_CASE						(							self				:Tuple     ):





        '''simple docstring'''




        self.config_tester.run_common_tests()



     @unittest.skip(reason="MobileNetV2 does not use inputs_embeds"     )
     def   SCREAMING_SNAKE_CASE						(							self				:Optional[int]     ):





        '''simple docstring'''




        pass



     @unittest.skip(reason="MobileNetV2 does not support input and output embeddings"     )
     def   SCREAMING_SNAKE_CASE						(							self				:Dict     ):





        '''simple docstring'''




        pass



     @unittest.skip(reason="MobileNetV2 does not output attentions"     )
     def   SCREAMING_SNAKE_CASE						(							self				:Optional[Any]     ):





        '''simple docstring'''




        pass



     def   SCREAMING_SNAKE_CASE						(							self				:Any     ):





        '''simple docstring'''




        A_					,  A_    : Optional[Any]								=	self.model_tester.prepare_config_and_inputs_for_common()

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

           A_    : str								=	["pixel_values"]
           self.assertListEqual(arg_names[:1]	,					_a     )



     def   SCREAMING_SNAKE_CASE						(							self				:Tuple     ):





        '''simple docstring'''




        A_    : Optional[int]								=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_a     )



     def   SCREAMING_SNAKE_CASE						(							self				:Dict     ):





        '''simple docstring'''




        def check_hidden_states_output(snake_case				:Optional[int]	,					snake_case				:Dict	,					snake_case				:Tuple     ):
           A_    : Union[str, Any]								=	model_class(_a     )
           model.to(_a     )
           model.eval()

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

           A_    : Optional[Any]								=	outputs.hidden_states

           A_    : Optional[Any]								=	16
           self.assertEqual(len(_a     )	,					_a     )

        A_					,  A_    : Optional[int]								=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           A_    : List[str]								=	True
           check_hidden_states_output(_a	,					_a	,					_a     )

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

           check_hidden_states_output(_a	,					_a	,					_a     )



     def   SCREAMING_SNAKE_CASE						(							self				:Tuple     ):





        '''simple docstring'''




        A_    : Dict								=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_a     )



     def   SCREAMING_SNAKE_CASE						(							self				:List[str]     ):





        '''simple docstring'''




        A_    : List[str]								=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*_a     )





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





        '''simple docstring'''




        for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           A_    : List[str]								=	MobileNetVaModel.from_pretrained(_a     )
           self.assertIsNotNone(_a     )




def    __snake_case  (    )       ->  Dict:
   A_    : int								=	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
   return image





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





     """simple docstring"""



     @cached_property
     def   SCREAMING_SNAKE_CASE						(							self				:Union[str, Any]     ):





        '''simple docstring'''




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



     @slow
     def   SCREAMING_SNAKE_CASE						(							self				:Union[str, Any]     ):





        '''simple docstring'''




        A_    : Any								=	MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"     ).to(_a     )

        A_    : int								=	self.default_image_processor
        A_    : List[str]								=	prepare_img()
        A_    : Tuple								=	image_processor(images=_a	,					return_tensors="pt"     ).to(_a     )

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

        # verify the logits
        A_    : Optional[int]								=	torch.Size((1, 1_001)     )
        self.assertEqual(outputs.logits.shape	,					_a     )

        A_    : Union[str, Any]								=	torch.tensor([0.2445, -1.1993, 0.1905]     ).to(_a     )

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





     @slow
     def   SCREAMING_SNAKE_CASE						(							self				:Tuple     ):





        '''simple docstring'''




        A_    : int								=	MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"     )
        A_    : Tuple								=	model.to(_a     )

        A_    : Tuple								=	MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"     )

        A_    : int								=	prepare_img()
        A_    : str								=	image_processor(images=_a	,					return_tensors="pt"     ).to(_a     )

        # forward pass
        with torch.no_grad():
           A_    : Any								=	model(**_a     )
        A_    : Optional[Any]								=	outputs.logits

        # verify the logits
        A_    : Optional[Any]								=	torch.Size((1, 21, 65, 65)     )
        self.assertEqual(logits.shape	,					_a     )

        A_    : Any								=	torch.tensor(
            [
                [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
                [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
                [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
            ]	,					device=_a	,					)

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




"""simple docstring"""




def        lowercase							(		lowerCAmelCase__ :     str    ,					lowerCAmelCase__ :     list[str]			) ->      str:
		__a           =			''''''
		for word_or_phrase in separated:
				if not isinstance(lowerCAmelCase__    ,					lowerCAmelCase__			):
						raise Exception('''join() accepts only strings to be joined'''			)
				joined += word_or_phrase + separator
		return joined.strip(lowerCAmelCase__			)


if __name__ == "__main__":
				from doctest import testmod

				testmod()






