


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





      def        _lowercase				(		self						:					Optional[Any]       )    ->   List[str]:






         """simple docstring"""







         UpperCAmelCase							=     self.config_class(**self.inputs_dict       )
         self.parent.assertTrue(hasattr(__lowerCamelCase					,       """tf_padding"""       )       )
         self.parent.assertTrue(hasattr(__lowerCamelCase					,       """depth_multiplier"""       )       )






class   __lowercase				:





      def __init__(		self						:					str					,       __lowerCamelCase						:					List[str]					,       __lowerCamelCase						:					List[str]=1_3					,       __lowerCamelCase						:					str=3					,       __lowerCamelCase						:					Union[str, Any]=3_2					,       __lowerCamelCase						:					List[Any]=0.25					,       __lowerCamelCase						:					Union[str, Any]=8					,       __lowerCamelCase						:					Union[str, Any]=True					,       __lowerCamelCase						:					str=1_0_2_4					,       __lowerCamelCase						:					Any=3_2					,       __lowerCamelCase						:					Optional[int]="relu6"					,       __lowerCamelCase						:					int=0.1					,       __lowerCamelCase						:					str=0.02					,       __lowerCamelCase						:					Any=True					,       __lowerCamelCase						:					int=True					,       __lowerCamelCase						:					Union[str, Any]=1_0					,       __lowerCamelCase						:					Union[str, Any]=None					,       )    ->   Tuple:






         """simple docstring"""







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





      def        _lowercase				(		self						:					Tuple       )    ->   Any:






         """simple docstring"""







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

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

         UpperCAmelCase							=     self.get_config()

         return config, pixel_values, labels, pixel_labels





      def        _lowercase				(		self						:					Tuple       )    ->   Optional[int]:






         """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						:					Any					,       __lowerCamelCase						:					int					,       __lowerCamelCase						:					List[Any]					,       __lowerCamelCase						:					Tuple					,       __lowerCamelCase						:					List[Any]       )    ->   List[Any]:






         """simple docstring"""







         UpperCAmelCase							=     MobileNetVaModel(config=__lowerCamelCase       )
         model.to(__lowerCamelCase       )
         model.eval()
         UpperCAmelCase							=     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						:					List[Any]					,       __lowerCamelCase						:					str					,       __lowerCamelCase						:					str					,       __lowerCamelCase						:					Union[str, Any]					,       __lowerCamelCase						:					int       )    ->   Union[str, Any]:






         """simple docstring"""







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





      def        _lowercase				(		self						:					str       )    ->   Tuple:






         """simple docstring"""







         UpperCAmelCase							=     self.prepare_config_and_inputs()
         UpperCAmelCase				,  UpperCAmelCase				,  UpperCAmelCase				,  UpperCAmelCase							=     config_and_inputs
         UpperCAmelCase							=     {"""pixel_values""": pixel_values}
         return config, inputs_dict






@require_torch
class   __lowercase				(  __snake_case ,					__snake_case ,					unittest.TestCase  ):
      UpperCamelCase								=       (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
      UpperCamelCase								=       (
          {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
          if is_torch_available()
          else {}
      )

      UpperCamelCase								=       False
      UpperCamelCase								=       False
      UpperCamelCase								=       False
      UpperCamelCase								=       False





      def        _lowercase				(		self						:					List[Any]       )    ->   Optional[int]:






         """simple docstring"""







         UpperCAmelCase							=     MobileNetVaModelTester(self       )
         UpperCAmelCase							=     MobileNetVaConfigTester(self					,       config_class=__lowerCamelCase					,       has_text_modality=__lowerCamelCase       )





      def        _lowercase				(		self						:					Optional[int]       )    ->   Tuple:






         """simple docstring"""







         self.config_tester.run_common_tests()





      @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""       )
      def        _lowercase				(		self						:					List[str]       )    ->   Optional[int]:






         """simple docstring"""







         pass





      @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""       )
      def        _lowercase				(		self						:					Union[str, Any]       )    ->   Tuple:






         """simple docstring"""







         pass





      @unittest.skip(reason="""MobileNetV1 does not output attentions"""       )
      def        _lowercase				(		self						:					List[Any]       )    ->   Optional[Any]:






         """simple docstring"""







         pass





      def        _lowercase				(		self						:					Dict       )    ->   Optional[int]:






         """simple docstring"""







         UpperCAmelCase				,  UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs_for_common()

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

            UpperCAmelCase							=     ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]					,       __lowerCamelCase       )





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






         """simple docstring"""







         UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__lowerCamelCase       )





      def        _lowercase				(		self						:					Dict       )    ->   str:






         """simple docstring"""







         def check_hidden_states_output(__lowerCamelCase						:					Union[str, Any]					,       __lowerCamelCase						:					str					,       __lowerCamelCase						:					Tuple       ):
            UpperCAmelCase							=     model_class(__lowerCamelCase       )
            model.to(__lowerCamelCase       )
            model.eval()

            with torch.no_grad():
               UpperCAmelCase							=     model(**self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase       )       )

            UpperCAmelCase							=     outputs.hidden_states

            UpperCAmelCase							=     2_6
            self.assertEqual(len(__lowerCamelCase       )					,       __lowerCamelCase       )

         UpperCAmelCase				,  UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase							=     True
            check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase       )

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

            check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase       )





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






         """simple docstring"""







         UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase       )





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






         """simple docstring"""







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

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







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





      @cached_property
      def        _lowercase				(		self						:					int       )    ->   Optional[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]       )    ->   Optional[int]:






         """simple docstring"""







         UpperCAmelCase							=     MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""       ).to(__lowerCamelCase       )

         UpperCAmelCase							=     self.default_image_processor
         UpperCAmelCase							=     prepare_img()
         UpperCAmelCase							=     image_processor(images=__lowerCamelCase					,       return_tensors="""pt"""       ).to(__lowerCamelCase       )

         # forward pass
         with torch.no_grad():
            UpperCAmelCase							=     model(**__lowerCamelCase       )

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

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

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







__a     =			[
    (1000, """M"""),
    (900, """CM"""),
    (500, """D"""),
    (400, """CD"""),
    (100, """C"""),
    (90, """XC"""),
    (50, """L"""),
    (40, """XL"""),
    (10, """X"""),
    (9, """IX"""),
    (5, """V"""),
    (4, """IV"""),
    (1, """I"""),
]
def   _UpperCamelCase				(						lowerCAmelCase_   )						->int:
   UpperCAmelCase							=     {"""I""": 1, """V""": 5, """X""": 1_0, """L""": 5_0, """C""": 1_0_0, """D""": 5_0_0, """M""": 1_0_0_0}
   UpperCAmelCase							=     0
   UpperCAmelCase							=     0
   while place < len(lowerCAmelCase_   ):
      if (place + 1 < len(lowerCAmelCase_   )) and (vals[roman[place]] < vals[roman[place + 1]]):
         total += vals[roman[place + 1]] - vals[roman[place]]
         place += 2
      else:
         total += vals[roman[place]]
         place += 1
   return total
def   _UpperCamelCase				(						lowerCAmelCase_   )						->str:
   UpperCAmelCase							=     []
   for arabic, roman in ROMAN:
      ((UpperCAmelCase)				,  (UpperCAmelCase))							=     divmod(lowerCAmelCase_  ,						lowerCAmelCase_   )
      result.append(roman * factor   )
      if number == 0:
         break
   return "".join(lowerCAmelCase_   )


if __name__ == "__main__":
 import doctest

 doctest.testmod()



