





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_				( _SCREAMING_SNAKE_CASE ):


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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





class UpperCAmelCase_				:


  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 ,):



       """simple docstring"""





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


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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

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

       A_          =       self.get_config()

       return config, pixel_values, labels, pixel_labels


  def 						__UpperCAmelCase     (							self ):



       """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 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ):



       """simple docstring"""





       A_          =       MobileNetVaModel(config=__snake_case )
       model.to(__snake_case )
       model.eval()
       A_          =       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 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ):



       """simple docstring"""





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




  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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





@require_torch
class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE     ,		_SCREAMING_SNAKE_CASE     ,		unittest.TestCase ):
  __lowerCAmelCase   :						Optional[Any]							=   (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
  __lowerCAmelCase   :						Any							=   (
      {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
      if is_torch_available()
      else {}
  )

  __lowerCAmelCase   :						Optional[Any]							=   False
  __lowerCAmelCase   :						Tuple							=   False
  __lowerCAmelCase   :						List[str]							=   False
  __lowerCAmelCase   :						str							=   False


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       self.config_tester.run_common_tests()


  @unittest.skip(reason='''MobileNetV1 does not use inputs_embeds''' )
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       pass


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



       """simple docstring"""





       pass


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



       """simple docstring"""





       pass


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_   ,    A_          =       self.model_tester.prepare_config_and_inputs_for_common()

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

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


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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

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

            A_          =       outputs.hidden_states

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

       A_   ,    A_          =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            A_          =       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"]
            A_          =       True

            check_hidden_states_output(__snake_case ,__snake_case ,__snake_case )


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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




  @slow
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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




def      UpperCAmelCase_    (    )	->				Dict:
     '''simple docstring'''


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





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


  @cached_property
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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




  @slow
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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

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

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

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

       A_          =       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 enum
import shutil
import sys


a__   ,				a__      :     int         =		shutil.get_terminal_size()

a__      :     Tuple         =		{'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'}





class UpperCAmelCase_				( enum.Enum ):
  __lowerCAmelCase   :						int							=   0
  __lowerCAmelCase   :						Optional[int]							=   1




def      UpperCAmelCase_    (    _UpperCAmelCase							:Optional[int]  ,						_UpperCAmelCase							:int=""				)	->				str:
     '''simple docstring'''


     sys.stdout.write(str(_UpperCAmelCase				) + end				)
     sys.stdout.flush()

def      UpperCAmelCase_    (    _UpperCAmelCase							:Union[str, Any]  ,						_UpperCAmelCase							:Tuple  ,						_UpperCAmelCase							:Tuple=""				)	->				List[Any]:
     '''simple docstring'''


     forceWrite(f'\u001b[{color}m{content}\u001b[0m'  ,						_UpperCAmelCase				)

def      UpperCAmelCase_    (    )	->				Dict:
     '''simple docstring'''


     forceWrite('''\r'''				)

def      UpperCAmelCase_    (    _UpperCAmelCase							:int  ,						_UpperCAmelCase							:str				)	->				List[Any]:
     '''simple docstring'''


     forceWrite(f'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}'				)

def      UpperCAmelCase_    (    )	->				List[Any]:
     '''simple docstring'''


     forceWrite(''' ''' * TERMINAL_WIDTH				)
     reset_cursor()


def      UpperCAmelCase_    (    )	->				Tuple:
     '''simple docstring'''


     reset_cursor()
     forceWrite('''-''' * TERMINAL_WIDTH				)



