





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 					A__   (       __snake_case			):





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					List[str]       	=   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 					A__   :





      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'''




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





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Any       	=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

       UpperCamelCase	:					List[str]       	=   self.get_config()

       return config, pixel_values, labels, pixel_labels





      def        __UpperCamelCase( 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        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_   ):
       '''simple docstring'''




       UpperCamelCase	:					Optional[int]       	=   MobileViTModel(config=A_   )
       model.to(A_   )
       model.eval()
       UpperCamelCase	:					Tuple       	=   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        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_   ):
       '''simple docstring'''




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





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_   ):
       '''simple docstring'''




       UpperCamelCase	:					List[Any]       	=   self.num_labels
       UpperCamelCase	:					Any       	=   MobileViTForSemanticSegmentation(A_   )
       model.to(A_   )
       model.eval()
       UpperCamelCase	:					Optional[int]       	=   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,
           )       ,							)
       UpperCamelCase	:					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        __UpperCamelCase( self   ):
       '''simple docstring'''




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



@require_torch
class 					A__   (       __snake_case       ,   __snake_case       ,   unittest.TestCase			):
      _UpperCAmelCase	:Union[str, Any]						    =   (
          (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
          if is_torch_available()
          else ()
      )
      _UpperCAmelCase	:Dict						    =   (
          {
              'feature-extraction': MobileViTModel,
              'image-classification': MobileViTForImageClassification,
              'image-segmentation': MobileViTForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      _UpperCAmelCase	:Tuple						    =   False
      _UpperCAmelCase	:int						    =   False
      _UpperCAmelCase	:Tuple						    =   False
      _UpperCAmelCase	:Union[str, Any]						    =   False





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Any       	=   MobileViTModelTester(self   )
       UpperCamelCase	:					int       	=   MobileViTConfigTester(self       ,							config_class=A_       ,							has_text_modality=A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       self.config_tester.run_common_tests()





      @unittest.skip(reason="MobileViT does not use inputs_embeds"   )
      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       pass





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




       pass





      @unittest.skip(reason="MobileViT does not output attentions"   )
      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       pass





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	,    UpperCamelCase	:					Any       	=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase	:					Optional[Any]       	=   model_class(A_   )
        UpperCamelCase	:					Optional[Any]       	=   inspect.signature(model.forward   )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        UpperCamelCase	:					Optional[int]       	=   [*signature.parameters.keys()]

        UpperCamelCase	:					Dict       	=   ["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        __UpperCamelCase( self   ):
       '''simple docstring'''




       pass





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Union[str, Any]       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       def check_hidden_states_output(A_       ,							A_       ,							A_   ):
        UpperCamelCase	:					Tuple       	=   model_class(A_   )
        model.to(A_   )
        model.eval()

        with torch.no_grad():
         UpperCamelCase	:					Dict       	=   model(**self._prepare_for_class(A_       ,							A_   )   )

        UpperCamelCase	:					str       	=   outputs.hidden_states

        UpperCamelCase	:					Optional[int]       	=   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.
        UpperCamelCase	:					Tuple       	=   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   )

       UpperCamelCase	,    UpperCamelCase	:					Any       	=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase	:					Union[str, Any]       	=   True
        check_hidden_states_output(A_       ,							A_       ,							A_   )

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

        check_hidden_states_output(A_       ,							A_       ,							A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Optional[Any]       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Dict       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*A_   )





      @slow
      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase	:					Tuple       	=   MobileViTModel.from_pretrained(A_   )
        self.assertIsNotNone(A_   )



def 		A_				(     )						-> Union[str, Any]:
 UpperCamelCase	:					Tuple       	=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
 return image



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





      @cached_property
      def        __UpperCamelCase( self   ):
       '''simple docstring'''




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





      @slow
      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					List[str]       	=   MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"   ).to(A_   )

       UpperCamelCase	:					List[Any]       	=   self.default_image_processor
       UpperCamelCase	:					Any       	=   prepare_img()
       UpperCamelCase	:					Union[str, Any]       	=   image_processor(images=A_       ,							return_tensors="pt"   ).to(A_   )

       # forward pass
       with torch.no_grad():
        UpperCamelCase	:					List[str]       	=   model(**A_   )

       # verify the logits
       UpperCamelCase	:					Union[str, Any]       	=   torch.Size((1, 1000)   )
       self.assertEqual(outputs.logits.shape       ,							A_   )

       UpperCamelCase	:					Any       	=   torch.tensor([-1.93_64, -1.23_27, -0.46_53]   ).to(A_   )

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





      @slow
      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Tuple       	=   MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"   )
       UpperCamelCase	:					str       	=   model.to(A_   )

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

       UpperCamelCase	:					Tuple       	=   prepare_img()
       UpperCamelCase	:					Dict       	=   image_processor(images=A_       ,							return_tensors="pt"   ).to(A_   )

       # forward pass
       with torch.no_grad():
        UpperCamelCase	:					Dict       	=   model(**A_   )
       UpperCamelCase	:					str       	=   outputs.logits

       # verify the logits
       UpperCamelCase	:					int       	=   torch.Size((1, 21, 32, 32)   )
       self.assertEqual(logits.shape       ,							A_   )

       UpperCamelCase	:					Any       	=   torch.tensor(
           [
               [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
               [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
               [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
           ]       ,							device=A_       ,							)

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





      @slow
      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					int       	=   MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"   )
       UpperCamelCase	:					Any       	=   model.to(A_   )

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

       UpperCamelCase	:					Union[str, Any]       	=   prepare_img()
       UpperCamelCase	:					Dict       	=   image_processor(images=A_       ,							return_tensors="pt"   ).to(A_   )

       # forward pass
       with torch.no_grad():
        UpperCamelCase	:					Tuple       	=   model(**A_   )

       UpperCamelCase	:					Tuple       	=   outputs.logits.detach().cpu()

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

       UpperCamelCase	:					List[str]       	=   image_processor.post_process_semantic_segmentation(outputs=A_   )
       UpperCamelCase	:					Optional[int]       	=   torch.Size((32, 32)   )
       self.assertEqual(segmentation[0].shape       ,							A_   )







def 		A_				(     _lowerCAmelCase     )						-> str:
 UpperCamelCase	:					List[Any]       	=   ""
 for ch in key:
  if ch == " " or ch not in key_no_dups and ch.isalpha():
   key_no_dups += ch
 return key_no_dups



def 		A_				(     _lowerCAmelCase     )						-> dict[str, str]:
 UpperCamelCase	:					Optional[Any]       	=   [chr(i + 65     ) for i in range(26     )]
 # Remove duplicate characters from key
 UpperCamelCase	:					Tuple       	=   remove_duplicates(key.upper()     )
 UpperCamelCase	:					int       	=   len(_lowerCAmelCase     )
 # First fill cipher with key characters
 UpperCamelCase	:					int       	=   {alphabet[i]: char for i, char in enumerate(_lowerCAmelCase     )}
 # Then map remaining characters in alphabet to
 # the alphabet from the beginning
 for i in range(len(_lowerCAmelCase     )							,   26     ):
  UpperCamelCase	:					Optional[Any]       	=   alphabet[i - offset]
  # Ensure we are not mapping letters to letters previously mapped
  while char in key:
   offset -= 1
   UpperCamelCase	:					List[str]       	=   alphabet[i - offset]
  UpperCamelCase	:					List[Any]       	=   char
 return cipher_alphabet



def 		A_				(     _lowerCAmelCase							,   _lowerCAmelCase     )						-> str:
 return "".join(cipher_map.get(_lowerCAmelCase							,   _lowerCAmelCase     ) for ch in message.upper()     )



def 		A_				(     _lowerCAmelCase							,   _lowerCAmelCase     )						-> str:
 UpperCamelCase	:					Union[str, Any]       	=   {v: k for k, v in cipher_map.items()}
 return "".join(rev_cipher_map.get(_lowerCAmelCase							,   _lowerCAmelCase     ) for ch in message.upper()     )



def 		A_				(     )						-> None:
 UpperCamelCase	:					int       	=   input("Enter message to encode or decode: "     ).strip()
 UpperCamelCase	:					str       	=   input("Enter keyword: "     ).strip()
 UpperCamelCase	:					Union[str, Any]       	=   input("Encipher or decipher? E/D:"     ).strip()[0].lower()
 try:
  UpperCamelCase	:					List[str]       	=   {"e": encipher, "d": decipher}[option]
 except KeyError:
  raise KeyError("invalid input option"     )
 UpperCamelCase	:					str       	=   create_cipher_map(_lowerCAmelCase     )
 print(func(_lowerCAmelCase							,   _lowerCAmelCase     )     )


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    main()
