


from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import numpy as np
     import tensorflow as tf

     from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
     from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import MobileViTImageProcessor







class 	_snake_case						(   __UpperCAmelCase							):




     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:List[Any]											= self.config_class(**self.inputs_dict					)
           self.parent.assertTrue(hasattr(lowercase_      ,						'''hidden_sizes'''					)					)
           self.parent.assertTrue(hasattr(lowercase_      ,						'''neck_hidden_sizes'''					)					)
           self.parent.assertTrue(hasattr(lowercase_      ,						'''num_attention_heads'''					)					)







class 	_snake_case						:




     def __init__(	self      ,						_lowerCamelCase      ,						_lowerCamelCase=13      ,						_lowerCamelCase=32      ,						_lowerCamelCase=2      ,						_lowerCamelCase=3      ,						_lowerCamelCase=640      ,						_lowerCamelCase=4      ,						_lowerCamelCase="silu"      ,						_lowerCamelCase=3      ,						_lowerCamelCase=32      ,						_lowerCamelCase=0.1      ,						_lowerCamelCase=0.1      ,						_lowerCamelCase=0.1      ,						_lowerCamelCase=0.02      ,						_lowerCamelCase=True      ,						_lowerCamelCase=True      ,						_lowerCamelCase=10      ,						_lowerCamelCase=None      ,						):
           a		:str											= parent
           a		:Optional[Any]											= batch_size
           a		:Union[str, Any]											= image_size
           a		:Optional[Any]											= patch_size
           a		:int											= num_channels
           a		:List[str]											= last_hidden_size
           a		:Optional[int]											= num_attention_heads
           a		:str											= hidden_act
           a		:Any											= conv_kernel_size
           a		:Tuple											= output_stride
           a		:List[Any]											= hidden_dropout_prob
           a		:List[str]											= attention_probs_dropout_prob
           a		:Dict											= classifier_dropout_prob
           a		:List[str]											= use_labels
           a		:Dict											= is_training
           a		:Optional[int]											= num_labels
           a		:Optional[Any]											= initializer_range
           a		:Union[str, Any]											= scope




     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Dict											= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

           a		:Any											= None
           a		:Dict											= None
           if self.use_labels:
                 a		:Any											= ids_tensor([self.batch_size]      ,						self.num_labels					)
                 a		:Tuple											= ids_tensor([self.batch_size, self.image_size, self.image_size]      ,						self.num_labels					)

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

           return config, pixel_values, labels, pixel_labels




     def  SCREAMING_SNAKE_CASE__       (	self					):
           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  SCREAMING_SNAKE_CASE__       (	self      ,						_lowerCamelCase      ,						_lowerCamelCase      ,						_lowerCamelCase      ,						_lowerCamelCase					):
           a		:int											= TFMobileViTModel(config=lowercase_					)
           a		:List[Any]											= model(lowercase_      ,						training=lowercase_					)
           a		:Any											= self.image_size // self.output_stride
           self.parent.assertEqual(
               result.last_hidden_state.shape      ,						(self.batch_size, self.last_hidden_size, expected_height, expected_width)					)




     def  SCREAMING_SNAKE_CASE__       (	self      ,						_lowerCamelCase      ,						_lowerCamelCase      ,						_lowerCamelCase      ,						_lowerCamelCase					):
           a		:Optional[Any]											= self.num_labels
           a		:Optional[Any]											= TFMobileViTForImageClassification(lowercase_					)
           a		:str											= model(lowercase_      ,						labels=lowercase_      ,						training=lowercase_					)
           self.parent.assertEqual(result.logits.shape      ,						(self.batch_size, self.num_labels)					)




     def  SCREAMING_SNAKE_CASE__       (	self      ,						_lowerCamelCase      ,						_lowerCamelCase      ,						_lowerCamelCase      ,						_lowerCamelCase					):
           a		:List[str]											= self.num_labels
           a		:int											= TFMobileViTForSemanticSegmentation(lowercase_					)
           a		:List[str]											= self.image_size // self.output_stride

           a		:Any											= model(lowercase_      ,						training=lowercase_					)
           self.parent.assertEqual(
               result.logits.shape      ,						(self.batch_size, self.num_labels, expected_height, expected_width)					)

           a		:Dict											= model(lowercase_      ,						labels=lowercase_      ,						training=lowercase_					)
           self.parent.assertEqual(
               result.logits.shape      ,						(self.batch_size, self.num_labels, expected_height, expected_width)					)




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







@require_tf
class 	_snake_case						(   __UpperCAmelCase		,					__UpperCAmelCase		,					unittest.TestCase							):
     SCREAMING_SNAKE_CASE__   = (
         (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
         if is_tf_available()
         else ()
     )
     SCREAMING_SNAKE_CASE__   = (
         {'feature-extraction': TFMobileViTModel, 'image-classification': TFMobileViTForImageClassification}
         if is_tf_available()
         else {}
     )

     SCREAMING_SNAKE_CASE__   = False
     SCREAMING_SNAKE_CASE__   = False
     SCREAMING_SNAKE_CASE__   = False
     SCREAMING_SNAKE_CASE__   = False
     SCREAMING_SNAKE_CASE__   = False




     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Tuple											= TFMobileViTModelTester(self					)
           a		:Any											= TFMobileViTConfigTester(self      ,						config_class=lowercase_      ,						has_text_modality=lowercase_					)




     def  SCREAMING_SNAKE_CASE__       (	self					):
           self.config_tester.run_common_tests()




     @unittest.skip(reason='''MobileViT does not use inputs_embeds'''					)
     def  SCREAMING_SNAKE_CASE__       (	self					):
           pass




     @unittest.skip(reason='''MobileViT does not support input and output embeddings'''					)
     def  SCREAMING_SNAKE_CASE__       (	self					):
           pass




     @unittest.skip(reason='''MobileViT does not output attentions'''					)
     def  SCREAMING_SNAKE_CASE__       (	self					):
           pass




     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Any											= self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 a		:Optional[int]											= model_class(lowercase_					)
                 a		:List[str]											= inspect.signature(model.call					)
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 a		:int											= [*signature.parameters.keys()]

                 a		:Tuple											= ['''pixel_values''']
                 self.assertListEqual(arg_names[:1]      ,						lowercase_					)




     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Dict											= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase_					)




     def  SCREAMING_SNAKE_CASE__       (	self					):

           def check_hidden_states_output(_lowerCamelCase      ,						_lowerCamelCase      ,						_lowerCamelCase					):
                 a		:Tuple											= model_class(lowercase_					)

                 a		:int											= model(**self._prepare_for_class(lowercase_      ,						lowercase_					)					)

                 a		:Optional[int]											= outputs.hidden_states

                 a		:int											= 5
                 self.assertEqual(len(lowercase_					)      ,						lowercase_					)

                 # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
                 # with the width and height being successively divided by 2.
                 a		:Dict											= 2
                 for i in range(len(lowercase_					)					):
                       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					)

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

           for model_class in self.all_model_classes:
                 a		:List[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		:Any											= True

                 check_hidden_states_output(lowercase_      ,						lowercase_      ,						lowercase_					)




     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Any											= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowercase_					)




     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Union[str, Any]											= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_					)




     @unittest.skipIf(
         not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''					)					) == 0      ,						reason='''TF does not support backprop for grouped convolutions on CPU.'''      ,						)
     def  SCREAMING_SNAKE_CASE__       (	self					):
           super().test_dataset_conversion()




     def  SCREAMING_SNAKE_CASE__       (	self      ,						_lowerCamelCase      ,						_lowerCamelCase      ,						_lowerCamelCase=2e-1      ,						_lowerCamelCase=2e-1					):
           self.assertTrue(np.allclose(lowercase_      ,						lowercase_      ,						atol=lowercase_      ,						rtol=lowercase_					)					)




     @unittest.skipIf(
         not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''					)					) == 0      ,						reason='''TF does not support backprop for grouped convolutions on CPU.'''      ,						)
     @slow
     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:int											= self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 # Since `TFMobileViTModel` cannot operate with the default `fit()` method.
                 if model_class.__name__ != "TFMobileViTModel":
                       a		:Union[str, Any]											= model_class(lowercase_					)
                       if getattr(lowercase_      ,						'''hf_compute_loss'''      ,						lowercase_					):
                             super().test_keras_fit()




     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Dict											= self.model_tester.prepare_config_and_inputs_for_common()
           for model_class in self.all_model_classes:
                 # set an ignore index to correctly test the masked loss used in
                 # `TFMobileViTForSemanticSegmentation`.
                 if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
                       a		:str											= 5

                 a		:str											= model_class(lowercase_					)
                 if getattr(lowercase_      ,						'''hf_compute_loss'''      ,						lowercase_					):
                       # The number of elements in the loss should be the same as the number of elements in the label
                       a		:List[Any]											= self._prepare_for_class(inputs_dict.copy()      ,						lowercase_      ,						return_labels=lowercase_					)
                       a		:str											= prepared_for_class[
                           sorted(prepared_for_class.keys() - inputs_dict.keys()      ,						reverse=lowercase_					)[0]
                       ]
                       a		:Tuple											= added_label.shape.as_list()[:1]

                       # Test that model correctly compute the loss with kwargs
                       a		:List[Any]											= self._prepare_for_class(inputs_dict.copy()      ,						lowercase_      ,						return_labels=lowercase_					)
                       a		:List[Any]											= {'''input_ids''', '''pixel_values''', '''input_features'''}
                       a		:Tuple											= possible_input_names.intersection(set(lowercase_					)					).pop()
                       a		:List[str]											= prepared_for_class.pop(lowercase_					)

                       a		:Any											= model(lowercase_      ,						**lowercase_					)[0]
                       self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)

                       # Test that model correctly compute the loss when we mask some positions
                       a		:Tuple											= self._prepare_for_class(inputs_dict.copy()      ,						lowercase_      ,						return_labels=lowercase_					)
                       a		:List[str]											= {'''input_ids''', '''pixel_values''', '''input_features'''}
                       a		:List[str]											= possible_input_names.intersection(set(lowercase_					)					).pop()
                       a		:str											= prepared_for_class.pop(lowercase_					)
                       if "labels" in prepared_for_class:
                             a		:Optional[int]											= prepared_for_class['''labels'''].numpy()
                             if len(labels.shape					) > 1 and labels.shape[1] != 1:
                                   # labels[0] = -100
                                   a		:Tuple											= tf.convert_to_tensor(lowercase_					)
                                   a		:Tuple											= model(lowercase_      ,						**lowercase_					)[0]
                                   self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)
                                   self.assertTrue(not np.any(np.isnan(loss.numpy()					)					)					)

                # Test that model correctly compute the loss with a dict
                       a		:List[Any]											= self._prepare_for_class(inputs_dict.copy()      ,						lowercase_      ,						return_labels=lowercase_					)
                       a		:Optional[Any]											= model(lowercase_					)[0]
                       self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)

                       # Test that model correctly compute the loss with a tuple
                       a		:Union[str, Any]											= self._prepare_for_class(inputs_dict.copy()      ,						lowercase_      ,						return_labels=lowercase_					)

                       # Get keys that were added with the _prepare_for_class function
                       a		:List[Any]											= prepared_for_class.keys() - inputs_dict.keys()
                       a		:Tuple											= inspect.signature(model.call					).parameters
                       a		:Dict											= list(signature.keys()					)

                       # Create a dictionary holding the location of the tensors in the tuple
                       a		:Optional[Any]											= {0: input_name}
                       for label_key in label_keys:
                             a		:Tuple											= signature_names.index(lowercase_					)
                             a		:Union[str, Any]											= label_key
                       a		:Optional[int]											= sorted(tuple_index_mapping.items()					)
                       # Initialize a list with their default values, update the values and convert to a tuple
                       a		:Tuple											= []

                       for name in signature_names:
                             if name != "kwargs":
                                   list_input.append(signature[name].default					)

                       for index, value in sorted_tuple_index_mapping:
                             a		:List[Any]											= prepared_for_class[value]

                       a		:Optional[int]											= tuple(lowercase_					)

                       # Send to model
                       a		:List[Any]											= model(tuple_input[:-1]					)[0]

                       self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)




     @slow
     def  SCREAMING_SNAKE_CASE__       (	self					):

           for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a		:Tuple											= TFMobileViTModel.from_pretrained(lowercase_					)
                 self.assertIsNotNone(lowercase_					)







def        __lowerCamelCase		(				):




      """simple docstring"""





      a		:List[str]											= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
      return image







@require_tf
class 	_snake_case						(   unittest.TestCase							):




     @slow
     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Tuple											= TFMobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''					)

           a		:Union[str, Any]											= MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''					)
           a		:Tuple											= prepare_img()
           a		:Dict											= image_processor(images=lowercase_      ,						return_tensors='''tf'''					)

           # forward pass
           a		:List[str]											= model(**lowercase_      ,						training=lowercase_					)

           # verify the logits
           a		:List[str]											= tf.TensorShape((1, 1000)					)
           self.assertEqual(outputs.logits.shape      ,						lowercase_					)

           a		:Any											= tf.constant([-1.9364, -1.2327, -0.4653]					)

           tf.debugging.assert_near(outputs.logits[0, :3]      ,						lowercase_      ,						atol=1e-4      ,						rtol=1e-04					)




     @slow
     def  SCREAMING_SNAKE_CASE__       (	self					):
           a		:Dict											= TFMobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)

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

           a		:List[str]											= prepare_img()
           a		:List[str]											= image_processor(images=lowercase_      ,						return_tensors='''tf'''					)

           # forward pass
           a		:str											= model(inputs.pixel_values      ,						training=lowercase_					)
           a		:Tuple											= outputs.logits

           # verify the logits
           a		:Dict											= tf.TensorShape((1, 21, 32, 32)					)
           self.assertEqual(logits.shape      ,						lowercase_					)

           a		:Optional[Any]											= tf.constant(
               [
                   [[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]],
               ]					)

           tf.debugging.assert_near(logits[0, :3, :3, :3]      ,						lowercase_      ,						rtol=1e-4      ,						atol=1e-4					)









import warnings

from ...utils import logging
from .image_processing_convnext import ConvNextImageProcessor


snake_case       :					Tuple        =  logging.get_logger(__name__)







class 	_snake_case						(   _snake_case							):




 def __init__(	self      ,						*_lowerCamelCase      ,						**_lowerCamelCase					):
       warnings.warn(
           '''The class ConvNextFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
           ''' Please use ConvNextImageProcessor instead.'''      ,						_lowerCamelCase      ,						)
       super().__init__(*_lowerCamelCase      ,						**_lowerCamelCase					)





