


import inspect
import unittest

from transformers import MobileViTConfig
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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
   from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import MobileViTImageProcessor
class 	UpperCAmelCase_					(					UpperCamelCase    ):

   '''simple docstring'''




   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					int    =				self.config_class(**self.inputs_dict )
     self.parent.assertTrue(hasattr(__A						,				"hidden_sizes" ) )
     self.parent.assertTrue(hasattr(__A						,				"neck_hidden_sizes" ) )
     self.parent.assertTrue(hasattr(__A						,				"num_attention_heads" ) )



class 	UpperCAmelCase_					:

   '''simple docstring'''




   def __init__(		self						,				__A						,				__A=13						,				__A=32						,				__A=2						,				__A=3						,				__A=640						,				__A=4						,				__A="silu"						,				__A=3						,				__A=32						,				__A=0.1						,				__A=0.1						,				__A=0.1						,				__A=0.02						,				__A=True						,				__A=True						,				__A=10						,				__A=None						,				):






     """simple docstring"""





     lowerCamelCase :					str    =				parent
     lowerCamelCase :					str    =				batch_size
     lowerCamelCase :					Dict    =				image_size
     lowerCamelCase :					Dict    =				patch_size
     lowerCamelCase :					Optional[int]    =				num_channels
     lowerCamelCase :					int    =				last_hidden_size
     lowerCamelCase :					Optional[int]    =				num_attention_heads
     lowerCamelCase :					int    =				hidden_act
     lowerCamelCase :					Optional[Any]    =				conv_kernel_size
     lowerCamelCase :					Tuple    =				output_stride
     lowerCamelCase :					Any    =				hidden_dropout_prob
     lowerCamelCase :					Optional[int]    =				attention_probs_dropout_prob
     lowerCamelCase :					Any    =				classifier_dropout_prob
     lowerCamelCase :					str    =				use_labels
     lowerCamelCase :					Optional[Any]    =				is_training
     lowerCamelCase :					str    =				num_labels
     lowerCamelCase :					Optional[Any]    =				initializer_range
     lowerCamelCase :					Dict    =				scope






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Dict    =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

     lowerCamelCase :					Optional[Any]    =				self.get_config()

     return config, pixel_values, labels, pixel_labels






   def _snake_case    (		self ):






     """simple docstring"""





     return MobileViTConfig(
         image_size=self.image_size						,				patch_size=self.patch_size						,				num_channels=self.num_channels						,				num_attention_heads=self.num_attention_heads						,				hidden_act=self.hidden_act						,				conv_kernel_size=self.conv_kernel_size						,				output_stride=self.output_stride						,				hidden_dropout_prob=self.hidden_dropout_prob						,				attention_probs_dropout_prob=self.attention_probs_dropout_prob						,				classifier_dropout_prob=self.classifier_dropout_prob						,				initializer_range=self.initializer_range						,				)






   def _snake_case    (		self						,				__A						,				__A						,				__A						,				__A ):






     """simple docstring"""





     lowerCamelCase :					Optional[Any]    =				MobileViTModel(config=__A )
     model.to(__A )
     model.eval()
     lowerCamelCase :					List[str]    =				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,
         )						,				)






   def _snake_case    (		self						,				__A						,				__A						,				__A						,				__A ):






     """simple docstring"""





     lowerCamelCase :					str    =				self.num_labels
     lowerCamelCase :					Union[str, Any]    =				MobileViTForImageClassification(__A )
     model.to(__A )
     model.eval()
     lowerCamelCase :					Any    =				model(__A						,				labels=__A )
     self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_labels) )






   def _snake_case    (		self						,				__A						,				__A						,				__A						,				__A ):






     """simple docstring"""





     lowerCamelCase :					Dict    =				self.num_labels
     lowerCamelCase :					Any    =				MobileViTForSemanticSegmentation(__A )
     model.to(__A )
     model.eval()
     lowerCamelCase :					Optional[Any]    =				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,
         )						,				)
     lowerCamelCase :					str    =				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 _snake_case    (		self ):






     """simple docstring"""





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



@require_torch
class 	UpperCAmelCase_					(					UpperCamelCase		, UpperCamelCase		, unittest.TestCase    ):

   '''simple docstring'''




   __A :      int     		=		(
       (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   __A :      str     		=		(
       {
           "feature-extraction": MobileViTModel,
           "image-classification": MobileViTForImageClassification,
           "image-segmentation": MobileViTForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __A :      Union[str, Any]     		=		False
   __A :      Dict     		=		False
   __A :      List[Any]     		=		False
   __A :      Union[str, Any]     		=		False






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				MobileViTModelTester(self )
     lowerCamelCase :					int    =				MobileViTConfigTester(self						,				config_class=__A						,				has_text_modality=__A )






   def _snake_case    (		self ):






     """simple docstring"""





     self.config_tester.run_common_tests()






   @unittest.skip(reason="MobileViT does not use inputs_embeds" )
   def _snake_case    (		self ):






     """simple docstring"""





     pass






   @unittest.skip(reason="MobileViT does not support input and output embeddings" )
   def _snake_case    (		self ):






     """simple docstring"""





     pass






   @unittest.skip(reason="MobileViT does not output attentions" )
   def _snake_case    (		self ):






     """simple docstring"""





     pass






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase    ,	lowerCamelCase :					Dict    =				self.model_tester.prepare_config_and_inputs_for_common()

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

       lowerCamelCase :					List[Any]    =				["pixel_values"]
       self.assertListEqual(arg_names[:1]						,				__A )






   @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
   def _snake_case    (		self ):






     """simple docstring"""





     pass






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Tuple    =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__A )






   def _snake_case    (		self ):






     """simple docstring"""





     def check_hidden_states_output(__A						,				__A						,				__A ):
       lowerCamelCase :					Tuple    =				model_class(__A )
       model.to(__A )
       model.eval()

       with torch.no_grad():
         lowerCamelCase :					List[Any]    =				model(**self._prepare_for_class(__A						,				__A ) )

       lowerCamelCase :					Union[str, Any]    =				outputs.hidden_states

       lowerCamelCase :					Dict    =				5
       self.assertEqual(len(__A )						,				__A )

       # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
       # with the width and height being successively divided by 2.
       lowerCamelCase :					Union[str, Any]    =				2
       for i in range(len(__A ) ):
         self.assertListEqual(
             list(hidden_states[i].shape[-2:] )						,				[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]						,				)
         divisor *= 2

       self.assertEqual(self.model_tester.output_stride						,				divisor // 2 )

     lowerCamelCase    ,	lowerCamelCase :					str    =				self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       lowerCamelCase :					Dict    =				True
       check_hidden_states_output(__A						,				__A						,				__A )

       # check that output_hidden_states also work using config
       del inputs_dict["output_hidden_states"]
       lowerCamelCase :					Any    =				True

       check_hidden_states_output(__A						,				__A						,				__A )






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					str    =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*__A )






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*__A )






   @slow
   def _snake_case    (		self ):






     """simple docstring"""





     for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       lowerCamelCase :					Dict    =				MobileViTModel.from_pretrained(__A )
       self.assertIsNotNone(__A )






def 		lowercase_(  ):


  '''simple docstring'''

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







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

   '''simple docstring'''




   @cached_property
   def _snake_case    (		self ):






     """simple docstring"""





     return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None






   @slow
   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[Any]    =				MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(__A )

     lowerCamelCase :					Dict    =				self.default_image_processor
     lowerCamelCase :					List[Any]    =				prepare_img()
     lowerCamelCase :					Optional[Any]    =				image_processor(images=__A						,				return_tensors="pt" ).to(__A )

     # forward pass
     with torch.no_grad():
       lowerCamelCase :					Union[str, Any]    =				model(**__A )

     # verify the logits
     lowerCamelCase :					Optional[int]    =				torch.Size((1, 1000) )
     self.assertEqual(outputs.logits.shape						,				__A )

     lowerCamelCase :					int    =				torch.tensor([-1.9364, -1.2327, -0.4653] ).to(__A )

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






   @slow
   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Optional[Any]    =				MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
     lowerCamelCase :					Tuple    =				model.to(__A )

     lowerCamelCase :					Tuple    =				MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )

     lowerCamelCase :					List[str]    =				prepare_img()
     lowerCamelCase :					List[Any]    =				image_processor(images=__A						,				return_tensors="pt" ).to(__A )

     # forward pass
     with torch.no_grad():
       lowerCamelCase :					Union[str, Any]    =				model(**__A )
     lowerCamelCase :					Any    =				outputs.logits

     # verify the logits
     lowerCamelCase :					List[str]    =				torch.Size((1, 21, 32, 32) )
     self.assertEqual(logits.shape						,				__A )

     lowerCamelCase :					Any    =				torch.tensor(
         [
             [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
             [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
             [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
         ]						,				device=__A						,				)

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






   @slow
   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Union[str, Any]    =				MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
     lowerCamelCase :					int    =				model.to(__A )

     lowerCamelCase :					Optional[Any]    =				MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )

     lowerCamelCase :					List[str]    =				prepare_img()
     lowerCamelCase :					List[str]    =				image_processor(images=__A						,				return_tensors="pt" ).to(__A )

     # forward pass
     with torch.no_grad():
       lowerCamelCase :					Tuple    =				model(**__A )

     lowerCamelCase :					int    =				outputs.logits.detach().cpu()

     lowerCamelCase :					int    =				image_processor.post_process_semantic_segmentation(outputs=__A						,				target_sizes=[(50, 60)] )
     lowerCamelCase :					int    =				torch.Size((50, 60) )
     self.assertEqual(segmentation[0].shape						,				__A )

     lowerCamelCase :					str    =				image_processor.post_process_semantic_segmentation(outputs=__A )
     lowerCamelCase :					int    =				torch.Size((32, 32) )
     self.assertEqual(segmentation[0].shape						,				__A )







import warnings

from ...utils import logging
from .image_processing_dpt import DPTImageProcessor


_snake_case             =     logging.get_logger(__name__)
class 	UpperCAmelCase_					(					UpperCamelCase    ):

   '''simple docstring'''




   def __init__(		self						,				*__A						,				**__A ):






     """simple docstring"""





     warnings.warn(
         "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
         " use DPTImageProcessor instead."						,				__A						,				)
     super().__init__(*__A						,				**__A )



