


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







    """simple docstring"""

    def 						a_     (			self       ):
         snake_case											=							self.config_class(**self.inputs_dict       )
         self.parent.assertTrue(hasattr(__snake_case     ,   '''tf_padding'''       )       )
         self.parent.assertTrue(hasattr(__snake_case     ,   '''depth_multiplier'''       )       )






class     A__   :







    """simple docstring"""

    def __init__(			self     ,   __snake_case     ,   __snake_case=1_3     ,   __snake_case=3     ,   __snake_case=3_2     ,   __snake_case=0.25     ,   __snake_case=8     ,   __snake_case=True     ,   __snake_case=1_0_2_4     ,   __snake_case=3_2     ,   __snake_case="relu6"     ,   __snake_case=0.1     ,   __snake_case=0.02     ,   __snake_case=True     ,   __snake_case=True     ,   __snake_case=1_0     ,   __snake_case=None     ,   ):
         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 						a_     (			self       ):
         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 						a_     (			self       ):
         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 						a_     (			self     ,   __snake_case     ,   __snake_case     ,   __snake_case     ,   __snake_case       ):
         snake_case											=							MobileNetVaModel(config=__snake_case       )
         model.to(__snake_case       )
         model.eval()
         snake_case											=							model(__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 						a_     (			self     ,   __snake_case     ,   __snake_case     ,   __snake_case     ,   __snake_case       ):
         snake_case											=							self.num_labels
         snake_case											=							MobileNetVaForImageClassification(__snake_case       )
         model.to(__snake_case       )
         model.eval()
         snake_case											=							model(__snake_case     ,   labels=__snake_case       )
         self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.num_labels)       )




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






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







    """simple docstring"""

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

    __magic_name__         =						False
    __magic_name__         =						False
    __magic_name__         =						False
    __magic_name__         =						False
    def 						a_     (			self       ):
         snake_case											=							MobileNetVaModelTester(self       )
         snake_case											=							MobileNetVaConfigTester(self     ,   config_class=__snake_case     ,   has_text_modality=__snake_case       )
    def 						a_     (			self       ):
         self.config_tester.run_common_tests()
    @unittest.skip(reason='''MobileNetV1 does not use inputs_embeds'''       )
    def 						a_     (			self       ):
         pass
    @unittest.skip(reason='''MobileNetV1 does not support input and output embeddings'''       )
    def 						a_     (			self       ):
         pass
    @unittest.skip(reason='''MobileNetV1 does not output attentions'''       )
    def 						a_     (			self       ):
         pass
    def 						a_     (			self       ):
         snake_case					,    snake_case											=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              snake_case											=							model_class(__snake_case       )
              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]     ,   __snake_case       )
    def 						a_     (			self       ):
         snake_case											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__snake_case       )
    def 						a_     (			self       ):
         def check_hidden_states_output(__snake_case     ,   __snake_case     ,   __snake_case       ):
              snake_case											=							model_class(__snake_case       )
              model.to(__snake_case       )
              model.eval()

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

              snake_case											=							outputs.hidden_states

              snake_case											=							2_6
              self.assertEqual(len(__snake_case       )     ,   __snake_case       )

         snake_case					,    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(__snake_case     ,   __snake_case     ,   __snake_case       )

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

              check_hidden_states_output(__snake_case     ,   __snake_case     ,   __snake_case       )
    def 						a_     (			self       ):
         snake_case											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__snake_case       )




    @slow
    def 						a_     (			self       ):
         for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              snake_case											=							MobileNetVaModel.from_pretrained(__snake_case       )
              self.assertIsNotNone(__snake_case       )






def      UpperCAmelCase__		():



     """simple docstring"""






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

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







    """simple docstring"""

    @cached_property
    def 						a_     (			self       ):
         return (
             MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v1_1.0_224'''       ) if is_vision_available() else None
         )




    @slow
    def 						a_     (			self       ):
         snake_case											=							MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224'''       ).to(__snake_case       )

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

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

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

         snake_case											=							torch.tensor([-4.1739, -1.1233, 3.1205]       ).to(__snake_case       )

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








import os
from distutils.util import strtobool
def      UpperCAmelCase__		(UpperCamelCase_				,UpperCamelCase_							):



     """simple docstring"""






     for e in env_keys:
          snake_case											=							int(os.environ.get(UpperCamelCase_				,-1							)							)
          if val >= 0:
               return val
     return default
def      UpperCAmelCase__		(UpperCamelCase_				,UpperCamelCase_=False							):



     """simple docstring"""






     snake_case											=							os.environ.get(UpperCamelCase_				,str(UpperCamelCase_							)							)
     return strtobool(UpperCamelCase_							) == 1  # As its name indicates `strtobool` actually returns an int...

def      UpperCAmelCase__		(UpperCamelCase_				,UpperCamelCase_="no"							):



     """simple docstring"""






     snake_case											=							os.environ.get(UpperCamelCase_				,str(UpperCamelCase_							)							)
     return value




