





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__   (							__UpperCAmelCase     ):




   """simple docstring"""



   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          a__						:     Tuple			=    self.config_class(**self.inputs_dict)
          self.parent.assertTrue(hasattr(lowercase ,  'tf_padding'))
          self.parent.assertTrue(hasattr(lowercase ,  'depth_multiplier'))





class 			A__   :




   """simple docstring"""



   def __init__( self ,  lowercase ,  lowercase=13 ,  lowercase=3 ,  lowercase=32 ,  lowercase=0.25 ,  lowercase=8 ,  lowercase=True ,  lowercase=1024 ,  lowercase=32 ,  lowercase="relu6" ,  lowercase=0.1 ,  lowercase=0.02 ,  lowercase=True ,  lowercase=True ,  lowercase=10 ,  lowercase=None ,  )      ->						List[str]:







          '''simple docstring'''

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

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Tuple			=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          a__						:     Any			=    self.get_config()

          return config, pixel_values, labels, pixel_labels

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







          '''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 ,  lowercase ,  lowercase ,  lowercase ,  lowercase)      ->						str:







          '''simple docstring'''

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







          '''simple docstring'''

          a__						:     Optional[int]			=    self.num_labels
          a__						:     Tuple			=    MobileNetVaForImageClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:     List[Any]			=    model(lowercase ,  labels=lowercase)
          self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.num_labels))

   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

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





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




   """simple docstring"""



   __A       :    Dict	  =  (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
   __A       :    Optional[Any]	  =  (
       {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
       if is_torch_available()
       else {}
   )

   __A       :    Union[str, Any]	  =  False
   __A       :    int	  =  False
   __A       :    Any	  =  False
   __A       :    Tuple	  =  False

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







          '''simple docstring'''

          a__						:     Tuple			=    MobileNetVaModelTester(self)
          a__						:     List[Any]			=    MobileNetVaConfigTester(self ,  config_class=lowercase ,  has_text_modality=lowercase)

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







          '''simple docstring'''

          self.config_tester.run_common_tests()

   @unittest.skip(reason='MobileNetV1 does not use inputs_embeds')
   def 							__lowercase		( self)      ->						List[str]:







          '''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)      ->						Tuple:







          '''simple docstring'''

          pass

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







          '''simple docstring'''

          a__			,							a__						:     List[str]			=    self.model_tester.prepare_config_and_inputs_for_common()

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

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

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







          '''simple docstring'''

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

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







          '''simple docstring'''

          def check_hidden_states_output(lowercase ,  lowercase ,  lowercase):
                 a__						:     int			=    model_class(lowercase)
                 model.to(lowercase)
                 model.eval()

                 with torch.no_grad():
                        a__						:     Optional[Any]			=    model(**self._prepare_for_class(lowercase ,  lowercase))

                 a__						:     List[Any]			=    outputs.hidden_states

                 a__						:     Tuple			=    26
                 self.assertEqual(len(lowercase) ,  lowercase)

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

          for model_class in self.all_model_classes:
                 a__						:     Union[str, Any]			=    True
                 check_hidden_states_output(lowercase ,  lowercase ,  lowercase)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 a__						:     Union[str, Any]			=    True

                 check_hidden_states_output(lowercase ,  lowercase ,  lowercase)

   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          a__						:     Optional[Any]			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase)

   @slow
   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:     Optional[int]			=    MobileNetVaModel.from_pretrained(lowercase)
                 self.assertIsNotNone(lowercase)



def A_     (		)  ->		Dict:
       a__						:     Tuple			=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
       return image





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




   """simple docstring"""



   @cached_property
   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

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

   @slow
   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     int			=    MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224').to(lowercase)

          a__						:     Tuple			=    self.default_image_processor
          a__						:     Union[str, Any]			=    prepare_img()
          a__						:     Tuple			=    image_processor(images=lowercase ,  return_tensors='pt').to(lowercase)

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

          # verify the logits
          a__						:     List[str]			=    torch.Size((1, 1001))
          self.assertEqual(outputs.logits.shape ,  lowercase)

          a__						:     Tuple			=    torch.tensor([-4.17_39, -1.12_33, 3.12_05]).to(lowercase)

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









def A_     (		A__		,				A__		,				A__    )  ->		float:
       if principal <= 0:
              raise Exception('Principal borrowed must be > 0'    )
       if rate_per_annum < 0:
              raise Exception('Rate of interest must be >= 0'    )
       if years_to_repay <= 0 or not isinstance(A__		,				A__    ):
              raise Exception('Years to repay must be an integer > 0'    )

       # Yearly rate is divided by 12 to get monthly rate
       a__						:     str			=    rate_per_annum / 12

       # Years to repay is multiplied by 12 to get number of payments as payment is monthly
       a__						:     List[Any]			=    years_to_repay * 12

       return (
           principal
           * rate_per_month
           * (1 + rate_per_month) ** number_of_payments
           / ((1 + rate_per_month) ** number_of_payments - 1)
       )


if __name__ == "__main__":
    import doctest

    doctest.testmod()


