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


   def 			lowercase_      (self     :						Any		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.config_class(**self.inputs_dict		)
         self.parent.assertTrue(hasattr(__UpperCAmelCase       ,  "tf_padding"		)		)
         self.parent.assertTrue(hasattr(__UpperCAmelCase       ,  "depth_multiplier"		)		)





class      A							:


   def __init__(self     :						Union[str, Any]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Any=1_3       ,  __UpperCAmelCase     :						str=3       ,  __UpperCAmelCase     :						List[Any]=3_2       ,  __UpperCAmelCase     :						List[str]=0.25       ,  __UpperCAmelCase     :						Any=8       ,  __UpperCAmelCase     :						Union[str, Any]=True       ,  __UpperCAmelCase     :						Optional[int]=1_0_2_4       ,  __UpperCAmelCase     :						Optional[int]=3_2       ,  __UpperCAmelCase     :						Tuple="relu6"       ,  __UpperCAmelCase     :						int=0.1       ,  __UpperCAmelCase     :						str=0.02       ,  __UpperCAmelCase     :						List[Any]=True       ,  __UpperCAmelCase     :						Union[str, Any]=True       ,  __UpperCAmelCase     :						Tuple=1_0       ,  __UpperCAmelCase     :						Optional[Any]=None       ,  )						->				Optional[Any]:
         """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     :						Optional[int]		)						->				List[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     :						Dict		)						->				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     :						Optional[int]       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						str       ,  __UpperCAmelCase     :						str		)						->				Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  MobileNetVaModel(config=__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()
         UpperCAmelCase__								=  model(__UpperCAmelCase		)
         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[str]       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						Tuple       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						Dict		)						->				int:
         """simple docstring"""



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





   def 			lowercase_      (self     :						Union[str, Any]		)						->				int:
         """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      A							(				UpperCAmelCase_		,				UpperCAmelCase_		,				unittest.TestCase     ):
   __UpperCAmelCase : Any      =			(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
   __UpperCAmelCase : str      =			(
       {'feature-extraction': MobileNetVaModel, 'image-classification': MobileNetVaForImageClassification}
       if is_torch_available()
       else {}
   )

   __UpperCAmelCase : Optional[int]      =			False
   __UpperCAmelCase : Any      =			False
   __UpperCAmelCase : int      =			False
   __UpperCAmelCase : Tuple      =			False


   def 			lowercase_      (self     :						Dict		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  MobileNetVaModelTester(self		)
         UpperCAmelCase__								=  MobileNetVaConfigTester(self       ,  config_class=__UpperCAmelCase       ,  has_text_modality=__UpperCAmelCase		)


   def 			lowercase_      (self     :						str		)						->				Dict:
         """simple docstring"""



         self.config_tester.run_common_tests()


   @unittest.skip(reason="MobileNetV1 does not use inputs_embeds"		)
   def 			lowercase_      (self     :						List[Any]		)						->				List[str]:
         """simple docstring"""



         pass


   @unittest.skip(reason="MobileNetV1 does not support input and output embeddings"		)
   def 			lowercase_      (self     :						List[str]		)						->				str:
         """simple docstring"""



         pass


   @unittest.skip(reason="MobileNetV1 does not output attentions"		)
   def 			lowercase_      (self     :						Any		)						->				Union[str, Any]:
         """simple docstring"""



         pass


   def 			lowercase_      (self     :						Tuple		)						->				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(__UpperCAmelCase		)
               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]       ,  __UpperCAmelCase		)


   def 			lowercase_      (self     :						Union[str, Any]		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__UpperCAmelCase		)


   def 			lowercase_      (self     :						List[Any]		)						->				Optional[int]:
         """simple docstring"""



         def check_hidden_states_output(__UpperCAmelCase     :						Tuple       ,  __UpperCAmelCase     :						Dict       ,  __UpperCAmelCase     :						Optional[int]		):
               UpperCAmelCase__								=  model_class(__UpperCAmelCase		)
               model.to(__UpperCAmelCase		)
               model.eval()

               with torch.no_grad():
                     UpperCAmelCase__								=  model(**self._prepare_for_class(__UpperCAmelCase       ,  __UpperCAmelCase		)		)

               UpperCAmelCase__								=  outputs.hidden_states

               UpperCAmelCase__								=  2_6
               self.assertEqual(len(__UpperCAmelCase		)       ,  __UpperCAmelCase		)

         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(__UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)

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

               check_hidden_states_output(__UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)


   def 			lowercase_      (self     :						str		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase		)





   @slow
   def 			lowercase_      (self     :						List[str]		)						->				Any:
         """simple docstring"""



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




def    lowerCAmelCase_ (     )     ->				Dict:







      '''simple docstring'''


      UpperCAmelCase__								=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
      return image







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


   @cached_property
   def 			lowercase_      (self     :						Optional[int]		)						->				int:
         """simple docstring"""



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





   @slow
   def 			lowercase_      (self     :						Optional[Any]		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224"		).to(__UpperCAmelCase		)

         UpperCAmelCase__								=  self.default_image_processor
         UpperCAmelCase__								=  prepare_img()
         UpperCAmelCase__								=  image_processor(images=__UpperCAmelCase       ,  return_tensors="pt"		).to(__UpperCAmelCase		)

         # forward pass
         with torch.no_grad():
               UpperCAmelCase__								=  model(**__UpperCAmelCase		)

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

         UpperCAmelCase__								=  torch.tensor([-4.1739, -1.1233, 3.1205]		).to(__UpperCAmelCase		)

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







import inspect
import warnings
from typing import Any, Dict, Optional, Union

from packaging import version


def   _SCREAMING_SNAKE_CASE	( *SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE = None ,			SCREAMING_SNAKE_CASE=True ,			SCREAMING_SNAKE_CASE=2       ):
  from .. import __version__

  A_      :				Union[str, Any]		     =					take_from
  A_      :				Optional[Any]		     =					()
  if not isinstance(args[0] ,			SCREAMING_SNAKE_CASE       ):
    A_      :				List[str]		     =					(args,)

  for attribute, version_name, message in args:
    if version.parse(version.parse(SCREAMING_SNAKE_CASE       ).base_version       ) >= version.parse(SCREAMING_SNAKE_CASE       ):
      raise ValueError(
          f'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\''''
          f''' version {__version__} is >= {version_name}'''       )

    A_      :				List[Any]		     =					None
    if isinstance(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       ) and attribute in deprecated_kwargs:
      values += (deprecated_kwargs.pop(SCREAMING_SNAKE_CASE       ),)
      A_      :				Optional[Any]		     =					f'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.'''
    elif hasattr(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       ):
      values += (getattr(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       ),)
      A_      :				int		     =					f'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.'''
    elif deprecated_kwargs is None:
      A_      :				List[Any]		     =					f'''`{attribute}` is deprecated and will be removed in version {version_name}.'''

    if warning is not None:
      A_      :				Union[str, Any]		     =					warning + ''' ''' if standard_warn else ''''''
      warnings.warn(warning + message ,			SCREAMING_SNAKE_CASE ,			stacklevel=SCREAMING_SNAKE_CASE       )

  if isinstance(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       ) and len(SCREAMING_SNAKE_CASE       ) > 0:
    A_      :				Dict		     =					inspect.getouterframes(inspect.currentframe()       )[1]
    A_      :				Optional[int]		     =					call_frame.filename
    A_      :				Optional[int]		     =					call_frame.lineno
    A_      :				str		     =					call_frame.function
    A_     ,       A_      :				List[str]		     =					next(iter(deprecated_kwargs.items()       )       )
    raise TypeError(f'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`'''       )

  if len(SCREAMING_SNAKE_CASE       ) == 0:
    return
  elif len(SCREAMING_SNAKE_CASE       ) == 1:
    return values[0]
  return values




