






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

       '''simple docstring'''



       def        __lowercase    (				self     )			->   Optional[Any]:






            '''simple docstring'''





            __snake_case      :str 							=    self.config_class(**self.inputs_dict     )
            self.parent.assertTrue(hasattr(_lowerCAmelCase      ,    """tf_padding"""     )     )
            self.parent.assertTrue(hasattr(_lowerCAmelCase      ,    """depth_multiplier"""     )     )




class       snake_case__ :

       '''simple docstring'''



       def __init__(				self      ,    a__      ,    a__=13      ,    a__=3      ,    a__=32      ,    a__=0.25      ,    a__=8      ,    a__=True      ,    a__=10_24      ,    a__=32      ,    a__="relu6"      ,    a__=0.1      ,    a__=0.02      ,    a__=True      ,    a__=True      ,    a__=10      ,    a__=None      ,    )			->   Optional[int]:






            '''simple docstring'''





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



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






            '''simple docstring'''





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

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

            __snake_case      :List[str] 							=    self.get_config()

            return config, pixel_values, labels, pixel_labels



       def        __lowercase    (				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        __lowercase    (				self      ,    a__      ,    a__      ,    a__      ,    a__     )			->   List[Any]:






            '''simple docstring'''





            __snake_case      :int 							=    MobileNetVaModel(config=_lowerCAmelCase     )
            model.to(_lowerCAmelCase     )
            model.eval()
            __snake_case      :Optional[int] 							=    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        __lowercase    (				self      ,    a__      ,    a__      ,    a__      ,    a__     )			->   str:






            '''simple docstring'''





            __snake_case      :Any 							=    self.num_labels
            __snake_case      :Dict 							=    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        __lowercase    (				self     )			->   List[Any]:






            '''simple docstring'''





            __snake_case      :Any 							=    self.prepare_config_and_inputs()
            __snake_case      :str 							=    config_and_inputs
            __snake_case      :Union[str, Any] 							=    {'''pixel_values''': pixel_values}
            return config, inputs_dict




@require_torch
class       snake_case__ (				__lowercase						,     __lowercase						,     unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase				:					List[str]								=			(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
       lowerCamelCase				:					Tuple								=			(
           {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
           if is_torch_available()
           else {}
       )

       lowerCamelCase				:					Optional[Any]								=			False
       lowerCamelCase				:					Any								=			False
       lowerCamelCase				:					int								=			False
       lowerCamelCase				:					List[Any]								=			False



       def        __lowercase    (				self     )			->   Optional[Any]:






            '''simple docstring'''





            __snake_case      :Union[str, Any] 							=    MobileNetVaModelTester(self     )
            __snake_case      :List[Any] 							=    MobileNetVaConfigTester(self      ,    config_class=_lowerCAmelCase      ,    has_text_modality=_lowerCAmelCase     )



       def        __lowercase    (				self     )			->   Dict:






            '''simple docstring'''





            self.config_tester.run_common_tests()



       @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""     )
       def        __lowercase    (				self     )			->   Any:






            '''simple docstring'''





            pass



       @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""     )
       def        __lowercase    (				self     )			->   Optional[Any]:






            '''simple docstring'''





            pass



       @unittest.skip(reason="""MobileNetV1 does not output attentions"""     )
       def        __lowercase    (				self     )			->   Any:






            '''simple docstring'''





            pass



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






            '''simple docstring'''





            __snake_case      :Any 							=    self.model_tester.prepare_config_and_inputs_for_common()

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

                 __snake_case      :List[str] 							=    ['''pixel_values''']
                 self.assertListEqual(arg_names[:1]      ,    _lowerCAmelCase     )



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






            '''simple docstring'''





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



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






            '''simple docstring'''





            def check_hidden_states_output(a__      ,    a__      ,    a__     ):
                 __snake_case      :str 							=    model_class(_lowerCAmelCase     )
                 model.to(_lowerCAmelCase     )
                 model.eval()

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

                 __snake_case      :Tuple 							=    outputs.hidden_states

                 __snake_case      :str 							=    26
                 self.assertEqual(len(_lowerCAmelCase     )      ,    _lowerCAmelCase     )

            __snake_case      :int 							=    self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 __snake_case      :Dict 							=    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      :str 							=    True

                 check_hidden_states_output(_lowerCAmelCase      ,    _lowerCAmelCase      ,    _lowerCAmelCase     )



       def        __lowercase    (				self     )			->   Union[str, Any]:






            '''simple docstring'''





            __snake_case      :Any 							=    self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase     )



       @slow
       def        __lowercase    (				self     )			->   Optional[int]:






            '''simple docstring'''





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






def 	UpperCamelCase	(							):




     '''simple docstring'''






     __snake_case      :Optional[Any] 							=    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
     return image




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

       '''simple docstring'''



       @cached_property
       def        __lowercase    (				self     )			->   int:






            '''simple docstring'''





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



       @slow
       def        __lowercase    (				self     )			->   Union[str, Any]:






            '''simple docstring'''





            __snake_case      :int 							=    MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""     ).to(_lowerCAmelCase     )

            __snake_case      :List[Any] 							=    self.default_image_processor
            __snake_case      :Tuple 							=    prepare_img()
            __snake_case      :List[Any] 							=    image_processor(images=_lowerCAmelCase      ,    return_tensors="""pt"""     ).to(_lowerCAmelCase     )

            # forward pass
            with torch.no_grad():
                 __snake_case      :List[str] 							=    model(**_lowerCAmelCase     )

            # verify the logits
            __snake_case      :List[str] 							=    torch.Size((1, 10_01)     )
            self.assertEqual(outputs.logits.shape      ,    _lowerCAmelCase     )

            __snake_case      :Optional[Any] 							=    torch.tensor([-4.17_39, -1.12_33, 3.12_05]     ).to(_lowerCAmelCase     )

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









def 		lowerCAmelCase  (	UpperCamelCase__   :   int       ,			UpperCamelCase__   :   float       ,			UpperCamelCase__   :   float					)      ->    float:

						"""simple docstring"""





						return round(float(moles / volume					) * nfactor					)






def 		lowerCAmelCase  (	UpperCamelCase__   :   float       ,			UpperCamelCase__   :   float       ,			UpperCamelCase__   :   float					)      ->    float:

						"""simple docstring"""





						return round(float((moles * 0.08_21 * temperature) / (volume)					)					)






def 		lowerCAmelCase  (	UpperCamelCase__   :   float       ,			UpperCamelCase__   :   float       ,			UpperCamelCase__   :   float					)      ->    float:

						"""simple docstring"""





						return round(float((moles * 0.08_21 * temperature) / (pressure)					)					)






def 		lowerCAmelCase  (	UpperCamelCase__   :   float       ,			UpperCamelCase__   :   float       ,			UpperCamelCase__   :   float					)      ->    float:

						"""simple docstring"""





						return round(float((pressure * volume) / (0.08_21 * moles)					)					)


if __name__ == "__main__":
							import doctest

							doctest.testmod()



