






'''simple docstring'''


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     SCREAMING_SNAKE_CASE						(	UpperCamelCase_							):






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           a_    :       Union[str, Any]    	=     self.config_class(**self.inputs_dict					)
           self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,	"""hidden_sizes"""					)					)
           self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,	"""neck_hidden_sizes"""					)					)
           self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,	"""num_attention_heads"""					)					)







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     Union[str, Any]	,	lowercase__      :     Optional[Any]	,	lowercase__      :     Dict=13	,	lowercase__      :     Any=32	,	lowercase__      :     List[Any]=2	,	lowercase__      :     List[str]=3	,	lowercase__      :     str=640	,	lowercase__      :     Tuple=4	,	lowercase__      :     Union[str, Any]="silu"	,	lowercase__      :     List[Any]=3	,	lowercase__      :     int=32	,	lowercase__      :     List[Any]=0.1	,	lowercase__      :     List[Any]=0.1	,	lowercase__      :     Optional[Any]=0.1	,	lowercase__      :     Optional[int]=0.02	,	lowercase__      :     List[Any]=True	,	lowercase__      :     int=True	,	lowercase__      :     List[Any]=10	,	lowercase__      :     List[Any]=None	,	):


           '''simple docstring'''

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






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           a_    :       int    	=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

           a_    :       Union[str, Any]    	=     self.get_config()

           return config, pixel_values, labels, pixel_labels






      def        lowercase_	(   self      :     Optional[Any]					):


           '''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        lowercase_	(   self      :     Dict	,	lowercase__      :     Union[str, Any]	,	lowercase__      :     Dict	,	lowercase__      :     List[str]	,	lowercase__      :     Dict					):


           '''simple docstring'''

           a_    :       Any    	=     TFMobileViTModel(config=__SCREAMING_SNAKE_CASE					)
           a_    :       Any    	=     model(__SCREAMING_SNAKE_CASE	,	training=__SCREAMING_SNAKE_CASE					)
           a_    :       List[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        lowercase_	(   self      :     Union[str, Any]	,	lowercase__      :     Optional[Any]	,	lowercase__      :     Optional[Any]	,	lowercase__      :     Dict	,	lowercase__      :     List[Any]					):


           '''simple docstring'''

           a_    :       Union[str, Any]    	=     self.num_labels
           a_    :       Union[str, Any]    	=     TFMobileViTForImageClassification(__SCREAMING_SNAKE_CASE					)
           a_    :       Optional[Any]    	=     model(__SCREAMING_SNAKE_CASE	,	labels=__SCREAMING_SNAKE_CASE	,	training=__SCREAMING_SNAKE_CASE					)
           self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.num_labels)					)






      def        lowercase_	(   self      :     Tuple	,	lowercase__      :     Tuple	,	lowercase__      :     int	,	lowercase__      :     Dict	,	lowercase__      :     Union[str, Any]					):


           '''simple docstring'''

           a_    :       List[Any]    	=     self.num_labels
           a_    :       Any    	=     TFMobileViTForSemanticSegmentation(__SCREAMING_SNAKE_CASE					)
           a_    :       List[Any]    	=     self.image_size // self.output_stride

           a_    :       Dict    	=     model(__SCREAMING_SNAKE_CASE	,	training=__SCREAMING_SNAKE_CASE					)
           self.parent.assertEqual(
               result.logits.shape	,	(self.batch_size, self.num_labels, expected_height, expected_width)					)

           a_    :       str    	=     model(__SCREAMING_SNAKE_CASE	,	labels=__SCREAMING_SNAKE_CASE	,	training=__SCREAMING_SNAKE_CASE					)
           self.parent.assertEqual(
               result.logits.shape	,	(self.batch_size, self.num_labels, expected_height, expected_width)					)






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

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







@require_tf
class     SCREAMING_SNAKE_CASE						(	UpperCamelCase_       ,			UpperCamelCase_       ,			unittest.TestCase							):
      __magic_name__     :					str             =				(
          (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
          if is_tf_available()
          else ()
      )
      __magic_name__     :					Dict             =				(
          {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
          if is_tf_available()
          else {}
      )

      __magic_name__     :					Optional[int]             =				False
      __magic_name__     :					Optional[Any]             =				False
      __magic_name__     :					str             =				False
      __magic_name__     :					Optional[int]             =				False
      __magic_name__     :					Union[str, Any]             =				False






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       List[str]    	=     TFMobileViTModelTester(self					)
           a_    :       Optional[int]    	=     TFMobileViTConfigTester(self	,	config_class=__SCREAMING_SNAKE_CASE	,	has_text_modality=__SCREAMING_SNAKE_CASE					)






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           self.config_tester.run_common_tests()






      @unittest.skip(reason="""MobileViT does not use inputs_embeds"""					)
      def        lowercase_	(   self      :     Union[str, Any]					):


           '''simple docstring'''

           pass






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


           '''simple docstring'''

           pass






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


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           a_	,    a_    :       Union[str, Any]    	=     self.model_tester.prepare_config_and_inputs_for_common()

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

                a_    :       Optional[Any]    	=     ["""pixel_values"""]
                self.assertListEqual(arg_names[:1]	,	__SCREAMING_SNAKE_CASE					)






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           a_    :       Tuple    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE					)






      def        lowercase_	(   self      :     Optional[Any]					):


           '''simple docstring'''

           def check_hidden_states_output(lowercase__      :     Optional[int]	,	lowercase__      :     Tuple	,	lowercase__      :     Tuple					):
                a_    :       int    	=     model_class(__SCREAMING_SNAKE_CASE					)

                a_    :       Optional[int]    	=     model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE	,	__SCREAMING_SNAKE_CASE					)					)

                a_    :       List[str]    	=     outputs.hidden_states

                a_    :       Optional[Any]    	=     5
                self.assertEqual(len(__SCREAMING_SNAKE_CASE					)	,	__SCREAMING_SNAKE_CASE					)

                # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
                # with the width and height being successively divided by 2.
                a_    :       Optional[int]    	=     2
                for i in range(len(__SCREAMING_SNAKE_CASE					)					):
                     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_	,    a_    :       str    	=     self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                a_    :       Optional[int]    	=     True
                check_hidden_states_output(__SCREAMING_SNAKE_CASE	,	__SCREAMING_SNAKE_CASE	,	__SCREAMING_SNAKE_CASE					)

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

                check_hidden_states_output(__SCREAMING_SNAKE_CASE	,	__SCREAMING_SNAKE_CASE	,	__SCREAMING_SNAKE_CASE					)






      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_for_image_classification(*__SCREAMING_SNAKE_CASE					)






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           a_    :       Optional[Any]    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE					)






      @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        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           super().test_dataset_conversion()






      def        lowercase_	(   self      :     Optional[int]	,	lowercase__      :     Optional[Any]	,	lowercase__      :     Optional[int]	,	lowercase__      :     Optional[Any]=2e-1	,	lowercase__      :     Tuple=2e-1					):


           '''simple docstring'''

           self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE	,	__SCREAMING_SNAKE_CASE	,	atol=__SCREAMING_SNAKE_CASE	,	rtol=__SCREAMING_SNAKE_CASE					)					)






      @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        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           a_	,    a_    :       List[Any]    	=     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_    :       str    	=     model_class(__SCREAMING_SNAKE_CASE					)
                     if getattr(__SCREAMING_SNAKE_CASE	,	"""hf_compute_loss"""	,	__SCREAMING_SNAKE_CASE					):
                          super().test_keras_fit()






      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           a_	,    a_    :       List[str]    	=     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_    :       Optional[int]    	=     5

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

                     # Test that model correctly compute the loss with kwargs
                     a_    :       Dict    	=     self._prepare_for_class(inputs_dict.copy()	,	__SCREAMING_SNAKE_CASE	,	return_labels=__SCREAMING_SNAKE_CASE					)
                     a_    :       List[str]    	=     {"""input_ids""", """pixel_values""", """input_features"""}
                     a_    :       Union[str, Any]    	=     possible_input_names.intersection(set(__SCREAMING_SNAKE_CASE					)					).pop()
                     a_    :       int    	=     prepared_for_class.pop(__SCREAMING_SNAKE_CASE					)

                     a_    :       int    	=     model(__SCREAMING_SNAKE_CASE	,	**__SCREAMING_SNAKE_CASE					)[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_    :       str    	=     self._prepare_for_class(inputs_dict.copy()	,	__SCREAMING_SNAKE_CASE	,	return_labels=__SCREAMING_SNAKE_CASE					)
                     a_    :       Dict    	=     {"""input_ids""", """pixel_values""", """input_features"""}
                     a_    :       Any    	=     possible_input_names.intersection(set(__SCREAMING_SNAKE_CASE					)					).pop()
                     a_    :       Any    	=     prepared_for_class.pop(__SCREAMING_SNAKE_CASE					)
                     if "labels" in prepared_for_class:
                          a_    :       Any    	=     prepared_for_class["""labels"""].numpy()
                          if len(labels.shape					) > 1 and labels.shape[1] != 1:
                               # labels[0] = -100
                               a_    :       Any    	=     tf.convert_to_tensor(__SCREAMING_SNAKE_CASE					)
                               a_    :       List[Any]    	=     model(__SCREAMING_SNAKE_CASE	,	**__SCREAMING_SNAKE_CASE					)[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_    :       Union[str, Any]    	=     self._prepare_for_class(inputs_dict.copy()	,	__SCREAMING_SNAKE_CASE	,	return_labels=__SCREAMING_SNAKE_CASE					)
                     a_    :       List[Any]    	=     model(__SCREAMING_SNAKE_CASE					)[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_    :       List[Any]    	=     self._prepare_for_class(inputs_dict.copy()	,	__SCREAMING_SNAKE_CASE	,	return_labels=__SCREAMING_SNAKE_CASE					)

                     # Get keys that were added with the _prepare_for_class function
                     a_    :       Optional[Any]    	=     prepared_for_class.keys() - inputs_dict.keys()
                     a_    :       Optional[int]    	=     inspect.signature(model.call					).parameters
                     a_    :       Any    	=     list(signature.keys()					)

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

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

                     for index, value in sorted_tuple_index_mapping:
                          a_    :       Optional[int]    	=     prepared_for_class[value]

                     a_    :       List[Any]    	=     tuple(__SCREAMING_SNAKE_CASE					)

                     # Send to model
                     a_    :       str    	=     model(tuple_input[:-1]					)[0]

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






      @slow
      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

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



def    _SCREAMING_SNAKE_CASE    (			):




     """simple docstring"""


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







@require_tf
class     SCREAMING_SNAKE_CASE						(	unittest.TestCase							):






      @slow
      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           a_    :       List[str]    	=     TFMobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""					)

           a_    :       Tuple    	=     MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""					)
           a_    :       List[Any]    	=     prepare_img()
           a_    :       Tuple    	=     image_processor(images=__SCREAMING_SNAKE_CASE	,	return_tensors="""tf"""					)

           # forward pass
           a_    :       int    	=     model(**__SCREAMING_SNAKE_CASE	,	training=__SCREAMING_SNAKE_CASE					)

           # verify the logits
           a_    :       int    	=     tf.TensorShape((1, 1000)					)
           self.assertEqual(outputs.logits.shape	,	__SCREAMING_SNAKE_CASE					)

           a_    :       Union[str, Any]    	=     tf.constant([-1.9364, -1.2327, -0.4653]					)

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






      @slow
      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           a_    :       Any    	=     TFMobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""					)

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

           a_    :       Optional[Any]    	=     prepare_img()
           a_    :       Union[str, Any]    	=     image_processor(images=__SCREAMING_SNAKE_CASE	,	return_tensors="""tf"""					)

           # forward pass
           a_    :       List[str]    	=     model(inputs.pixel_values	,	training=__SCREAMING_SNAKE_CASE					)
           a_    :       Any    	=     outputs.logits

           # verify the logits
           a_    :       List[str]    	=     tf.TensorShape((1, 21, 32, 32)					)
           self.assertEqual(logits.shape	,	__SCREAMING_SNAKE_CASE					)

           a_    :       str    	=     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]	,	__SCREAMING_SNAKE_CASE	,	rtol=1e-4	,	atol=1e-4					)






'''simple docstring'''


from .stack import Stack



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				str							):




     """simple docstring"""


     a_    :       Stack[str]    	=     Stack()
     a_    :       Tuple    	=     {"""(""": """)""", """[""": """]""", """{""": """}"""}
     for bracket in parentheses:
          if bracket in bracket_pairs:
               stack.push(UpperCamelCase__							)
          elif bracket in (")", "]", "}"):
               if stack.is_empty() or bracket_pairs[stack.pop()] != bracket:
                    return False
     return stack.is_empty()


if __name__ == "__main__":
 from doctest import testmod

 testmod()

 lowerCAmelCase_			:     Any							    =     ['((()))', '((())', '(()))']
 print('Balanced parentheses demonstration:\n')
 for example in examples:
  lowerCAmelCase_			:     Optional[Any]							    =     '' if balanced_parentheses(example) else 'not '
  print(f"{example} is {not_str}balanced")
