



'''simple docstring'''





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, MobileNetVaForSemanticSegmentation, MobileNetVaModel
  from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import MobileNetVaImageProcessor






class __A    (						A		):



 '''simple docstring'''







 def       a__						(self )					->  Tuple:


      """simple docstring"""



      _a											=						self.config_class(**self.inputs_dict )
      self.parent.assertTrue(hasattr(A				,     '''tf_padding''' ) )
      self.parent.assertTrue(hasattr(A				,     '''depth_multiplier''' ) )






class __A    :



 '''simple docstring'''







 def __init__(self				,     A				,     A=13				,     A=3				,     A=32				,     A=0.25				,     A=8				,     A=8				,     A=6				,     A=32				,     A=True				,     A=True				,     A=True				,     A="relu6"				,     A=1_280				,     A=0.1				,     A=0.02				,     A=True				,     A=True				,     A=10				,     A=None				,     )					->  Optional[Any]:


      """simple docstring"""



      _a											=						parent
      _a											=						batch_size
      _a											=						num_channels
      _a											=						image_size
      _a											=						depth_multiplier
      _a											=						depth_divisible_by
      _a											=						min_depth
      _a											=						expand_ratio
      _a											=						tf_padding
      _a											=						output_stride
      _a											=						first_layer_is_expansion
      _a											=						finegrained_output
      _a											=						hidden_act
      _a											=						last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier )
      _a											=						classifier_dropout_prob
      _a											=						use_labels
      _a											=						is_training
      _a											=						num_labels
      _a											=						initializer_range
      _a											=						scope



 def       a__						(self )					->  Dict:


      """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       a__						(self )					->  str:


      """simple docstring"""



      return MobileNetVaConfig(
          num_channels=self.num_channels				,     image_size=self.image_size				,     depth_multiplier=self.depth_multiplier				,     depth_divisible_by=self.depth_divisible_by				,     min_depth=self.min_depth				,     expand_ratio=self.expand_ratio				,     output_stride=self.output_stride				,     first_layer_is_expansion=self.first_layer_is_expansion				,     finegrained_output=self.finegrained_output				,     hidden_act=self.hidden_act				,     tf_padding=self.tf_padding				,     classifier_dropout_prob=self.classifier_dropout_prob				,     initializer_range=self.initializer_range				,     )



 def       a__						(self				,     A				,     A				,     A				,     A )					->  Any:


      """simple docstring"""



      _a											=						MobileNetVaModel(config=A )
      model.to(A )
      model.eval()
      _a											=						model(A )
      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,
          )				,     )
      self.parent.assertEqual(
          result.pooler_output.shape				,     (self.batch_size, self.last_hidden_size)				,     )



 def       a__						(self				,     A				,     A				,     A				,     A )					->  Tuple:


      """simple docstring"""



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



 def       a__						(self				,     A				,     A				,     A				,     A )					->  Optional[Any]:


      """simple docstring"""



      _a											=						self.num_labels
      _a											=						MobileNetVaForSemanticSegmentation(A )
      model.to(A )
      model.eval()
      _a											=						model(A )
      self.parent.assertEqual(
          result.logits.shape				,     (
              self.batch_size,
              self.num_labels,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )				,     )
      _a											=						model(A				,     labels=A )
      self.parent.assertEqual(
          result.logits.shape				,     (
              self.batch_size,
              self.num_labels,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )				,     )



 def       a__						(self )					->  str:


      """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 __A    (						A     ,     A     ,     unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase					: List[str]    = (
     (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
     if is_torch_available()
     else ()
 )
 __lowerCamelCase					: str    = (
     {
         'feature-extraction': MobileNetVaModel,
         'image-classification': MobileNetVaForImageClassification,
         'image-segmentation': MobileNetVaForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 __lowerCamelCase					: Optional[Any]    = False
 __lowerCamelCase					: List[Any]    = False
 __lowerCamelCase					: List[str]    = False
 __lowerCamelCase					: Dict    = False



 def       a__						(self )					->  List[str]:


      """simple docstring"""



      _a											=						MobileNetVaModelTester(self )
      _a											=						MobileNetVaConfigTester(self				,     config_class=A				,     has_text_modality=A )



 def       a__						(self )					->  int:


      """simple docstring"""



      self.config_tester.run_common_tests()



 @unittest.skip(reason='''MobileNetV2 does not use inputs_embeds''' )
 def       a__						(self )					->  Any:


      """simple docstring"""



      pass



 @unittest.skip(reason='''MobileNetV2 does not support input and output embeddings''' )
 def       a__						(self )					->  Dict:


      """simple docstring"""



      pass



 @unittest.skip(reason='''MobileNetV2 does not output attentions''' )
 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      pass



 def       a__						(self )					->  List[str]:


      """simple docstring"""



      _a						,					_a											=						self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           _a											=						model_class(A )
           _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]				,     A )



 def       a__						(self )					->  int:


      """simple docstring"""



      _a											=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A )



 def       a__						(self )					->  List[str]:


      """simple docstring"""



      def check_hidden_states_output(A				,     A				,     A ):
           _a											=						model_class(A )
           model.to(A )
           model.eval()

           with torch.no_grad():
                _a											=						model(**self._prepare_for_class(A				,     A ) )

           _a											=						outputs.hidden_states

           _a											=						16
           self.assertEqual(len(A )				,     A )

      _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(A				,     A				,     A )

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

           check_hidden_states_output(A				,     A				,     A )



 def       a__						(self )					->  Dict:


      """simple docstring"""



      _a											=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*A )



 def       a__						(self )					->  List[Any]:


      """simple docstring"""



      _a											=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*A )



 @slow
 def       a__						(self )					->  List[Any]:


      """simple docstring"""



      for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _a											=						MobileNetVaModel.from_pretrained(A )
           self.assertIsNotNone(A )





def lowerCAmelCase						():



     """simple docstring"""



     _a											=						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 )					->  Union[str, Any]:


      """simple docstring"""



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



 @slow
 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      _a											=						MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224''' ).to(A )

      _a											=						self.default_image_processor
      _a											=						prepare_img()
      _a											=						image_processor(images=A				,     return_tensors='''pt''' ).to(A )

      # forward pass
      with torch.no_grad():
           _a											=						model(**A )

      # verify the logits
      _a											=						torch.Size((1, 1_001) )
      self.assertEqual(outputs.logits.shape				,     A )

      _a											=						torch.tensor([0.2445, -1.1993, 0.1905] ).to(A )

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



 @slow
 def       a__						(self )					->  Optional[Any]:


      """simple docstring"""



      _a											=						MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' )
      _a											=						model.to(A )

      _a											=						MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' )

      _a											=						prepare_img()
      _a											=						image_processor(images=A				,     return_tensors='''pt''' ).to(A )

      # forward pass
      with torch.no_grad():
           _a											=						model(**A )
      _a											=						outputs.logits

      # verify the logits
      _a											=						torch.Size((1, 21, 65, 65) )
      self.assertEqual(logits.shape				,     A )

      _a											=						torch.tensor(
          [
              [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
              [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
              [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
          ]				,     device=A				,     )

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








'''simple docstring'''





import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image


if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
  lowercase_	 =						{
      "linear": PIL.Image.Resampling.BILINEAR,
      "bilinear": PIL.Image.Resampling.BILINEAR,
      "bicubic": PIL.Image.Resampling.BICUBIC,
      "lanczos": PIL.Image.Resampling.LANCZOS,
      "nearest": PIL.Image.Resampling.NEAREST,
  }
else:
  lowercase_	 =						{
      "linear": PIL.Image.LINEAR,
      "bilinear": PIL.Image.BILINEAR,
      "bicubic": PIL.Image.BICUBIC,
      "lanczos": PIL.Image.LANCZOS,
      "nearest": PIL.Image.NEAREST,
  }




def lowerCAmelCase						(__A):



     """simple docstring"""



     _a											=						(images / 2 + 0.5).clamp(0						,			1)
     _a											=						images.cpu().permute(0						,			2						,			3						,			1).float().numpy()
     _a											=						numpy_to_pil(__A)
     return images




def lowerCAmelCase						(__A):



     """simple docstring"""



     if images.ndim == 3:
          _a											=						images[None, ...]
     _a											=						(images * 255).round().astype('''uint8''')
     if images.shape[-1] == 1:
          # special case for grayscale (single channel) images
          _a											=						[Image.fromarray(image.squeeze()						,			mode='''L''') for image in images]
     else:
          _a											=						[Image.fromarray(__A) for image in images]

     return pil_images



