

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





    def 				snake_case_    (				self):
         lowercase__   :       Union[str, Any]				=	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 				SCREAMING_SNAKE_CASE__ :





    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						,       ):
         lowercase__   :       int				=	parent
         lowercase__   :       Optional[Any]				=	batch_size
         lowercase__   :       str				=	image_size
         lowercase__   :       Optional[int]				=	patch_size
         lowercase__   :       Dict				=	num_channels
         lowercase__   :       Optional[int]				=	last_hidden_size
         lowercase__   :       List[str]				=	num_attention_heads
         lowercase__   :       Optional[int]				=	hidden_act
         lowercase__   :       Union[str, Any]				=	conv_kernel_size
         lowercase__   :       Any				=	output_stride
         lowercase__   :       Union[str, Any]				=	hidden_dropout_prob
         lowercase__   :       Dict				=	attention_probs_dropout_prob
         lowercase__   :       List[Any]				=	classifier_dropout_prob
         lowercase__   :       List[str]				=	use_labels
         lowercase__   :       int				=	is_training
         lowercase__   :       Union[str, Any]				=	num_labels
         lowercase__   :       Optional[Any]				=	initializer_range
         lowercase__   :       Union[str, Any]				=	scope





    def 				snake_case_    (				self):
         lowercase__   :       Tuple				=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

         lowercase__   :       Union[str, Any]				=	None
         lowercase__   :       Optional[Any]				=	None
         if self.use_labels:
              lowercase__   :       Dict				=	ids_tensor([self.batch_size]						,       self.num_labels)
              lowercase__   :       List[str]				=	ids_tensor([self.batch_size, self.image_size, self.image_size]						,       self.num_labels)

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

         return config, pixel_values, labels, pixel_labels





    def 				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 				snake_case_    (				self						,       a						,       a						,       a						,       a):
         lowercase__   :       str				=	MobileViTModel(config=a)
         model.to(a)
         model.eval()
         lowercase__   :       Optional[int]				=	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):
         lowercase__   :       Any				=	self.num_labels
         lowercase__   :       Union[str, Any]				=	MobileViTForImageClassification(a)
         model.to(a)
         model.eval()
         lowercase__   :       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):
         lowercase__   :       Union[str, Any]				=	self.num_labels
         lowercase__   :       int				=	MobileViTForSemanticSegmentation(a)
         model.to(a)
         model.eval()
         lowercase__   :       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,
             )						,       )
         lowercase__   :       List[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):
         lowercase__   :       Any				=	self.prepare_config_and_inputs()
         lowercase__   :       Union[str, Any]				=	config_and_inputs
         lowercase__   :       Optional[int]				=	{'pixel_values': pixel_values}
         return config, inputs_dict



@require_torch
class 				SCREAMING_SNAKE_CASE__ (__snake_case		,	__snake_case		,	unittest.TestCase					):
    __lowerCamelCase						:	Tuple														=					(
        (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
        if is_torch_available()
        else ()
    )
    __lowerCamelCase						:	Tuple														=					(
        {
            """feature-extraction""": MobileViTModel,
            """image-classification""": MobileViTForImageClassification,
            """image-segmentation""": MobileViTForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    __lowerCamelCase						:	str														=					False
    __lowerCamelCase						:	Optional[Any]														=					False
    __lowerCamelCase						:	List[Any]														=					False
    __lowerCamelCase						:	Union[str, Any]														=					False





    def 				snake_case_    (				self):
         lowercase__   :       Any				=	MobileViTModelTester(self)
         lowercase__   :       Optional[Any]				=	MobileViTConfigTester(self						,       config_class=a						,       has_text_modality=a)





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





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





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





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





    def 				snake_case_    (				self):
         lowercase__   :       Tuple				=	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              lowercase__   :       List[Any]				=	model_class(a)
              lowercase__   :       List[Any]				=	inspect.signature(model.forward)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              lowercase__   :       Dict				=	[*signature.parameters.keys()]

              lowercase__   :       Union[str, 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):
         pass





    def 				snake_case_    (				self):
         lowercase__   :       Union[str, Any]				=	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a)





    def 				snake_case_    (				self):
         def check_hidden_states_output(a						,       a						,       a):
              lowercase__   :       Dict				=	model_class(a)
              model.to(a)
              model.eval()

              with torch.no_grad():
                   lowercase__   :       Dict				=	model(**self._prepare_for_class(a						,       a))

              lowercase__   :       List[str]				=	outputs.hidden_states

              lowercase__   :       List[str]				=	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.
              lowercase__   :       int				=	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)

         lowercase__   :       Any				=	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              lowercase__   :       str				=	True
              check_hidden_states_output(a						,       a						,       a)

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

              check_hidden_states_output(a						,       a						,       a)





    def 				snake_case_    (				self):
         lowercase__   :       Union[str, Any]				=	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*a)





    def 				snake_case_    (				self):
         lowercase__   :       Tuple				=	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*a)





    @slow
    def 				snake_case_    (				self):
         for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              lowercase__   :       Optional[int]				=	MobileViTModel.from_pretrained(a)
              self.assertIsNotNone(a)



def      snake_case__      (   ):



     '''simple docstring'''





     lowercase__   :       Union[str, Any]				=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
     return image


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





    @cached_property
    def 				snake_case_    (				self):
         return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small') if is_vision_available() else None





    @slow
    def 				snake_case_    (				self):
         lowercase__   :       Union[str, Any]				=	MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small').to(a)

         lowercase__   :       Union[str, Any]				=	self.default_image_processor
         lowercase__   :       int				=	prepare_img()
         lowercase__   :       Any				=	image_processor(images=a						,       return_tensors='pt').to(a)

         # forward pass
         with torch.no_grad():
              lowercase__   :       Tuple				=	model(**a)

         # verify the logits
         lowercase__   :       Optional[Any]				=	torch.Size((1, 1000))
         self.assertEqual(outputs.logits.shape						,       a)

         lowercase__   :       List[str]				=	torch.tensor([-1.9_364, -1.2_327, -0.4_653]).to(a)

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





    @slow
    def 				snake_case_    (				self):
         lowercase__   :       Union[str, Any]				=	MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small')
         lowercase__   :       int				=	model.to(a)

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

         lowercase__   :       Dict				=	prepare_img()
         lowercase__   :       Union[str, Any]				=	image_processor(images=a						,       return_tensors='pt').to(a)

         # forward pass
         with torch.no_grad():
              lowercase__   :       Any				=	model(**a)
         lowercase__   :       Optional[Any]				=	outputs.logits

         # verify the logits
         lowercase__   :       Any				=	torch.Size((1, 21, 32, 32))
         self.assertEqual(logits.shape						,       a)

         lowercase__   :       Optional[int]				=	torch.tensor(
             [
                 [[6.9_713, 6.9_786, 7.2_422], [7.2_893, 7.2_825, 7.4_446], [7.6_580, 7.8_797, 7.9_420]],
                 [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_868, -9.7_132], [-11.0_405, -11.0_221, -10.7_318]],
                 [[-3.3_089, -2.8_539, -2.6_740], [-3.2_706, -2.5_621, -2.5_108], [-3.2_534, -2.6_615, -2.6_651]],
             ]						,       device=a						,       )

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





    @slow
    def 				snake_case_    (				self):
         lowercase__   :       Dict				=	MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small')
         lowercase__   :       int				=	model.to(a)

         lowercase__   :       Union[str, Any]				=	MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small')

         lowercase__   :       List[Any]				=	prepare_img()
         lowercase__   :       List[Any]				=	image_processor(images=a						,       return_tensors='pt').to(a)

         # forward pass
         with torch.no_grad():
              lowercase__   :       Tuple				=	model(**a)

         lowercase__   :       Optional[Any]				=	outputs.logits.detach().cpu()

         lowercase__   :       List[Any]				=	image_processor.post_process_semantic_segmentation(outputs=a						,       target_sizes=[(50, 60)])
         lowercase__   :       List[str]				=	torch.Size((50, 60))
         self.assertEqual(segmentation[0].shape						,       a)

         lowercase__   :       Union[str, Any]				=	image_processor.post_process_semantic_segmentation(outputs=a)
         lowercase__   :       List[Any]				=	torch.Size((32, 32))
         self.assertEqual(segmentation[0].shape						,       a)




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


snake_case_        =			logging.get_logger(__name__)


if is_vision_available():
       import PIL


class 				SCREAMING_SNAKE_CASE__ (__snake_case					):
    __lowerCamelCase						:	Optional[Any]														=					["""pixel_values"""]





    def __init__(				self						,       a = True						,       a = None						,       a = PILImageResampling.BICUBIC						,       a = True						,       a = None						,       a = True						,       a = 1 / 255						,       a = True						,       a = None						,       a = None						,       a = True						,       **a						,       ):
         super().__init__(**a)
         lowercase__   :       List[str]				=	size if size is not None else {'shortest_edge': 224}
         lowercase__   :       str				=	get_size_dict(a						,       default_to_square=a)
         lowercase__   :       Optional[int]				=	crop_size if crop_size is not None else {'height': 224, 'width': 224}
         lowercase__   :       Union[str, Any]				=	get_size_dict(a						,       default_to_square=a						,       param_name='crop_size')

         lowercase__   :       List[str]				=	do_resize
         lowercase__   :       List[Any]				=	size
         lowercase__   :       Tuple				=	resample
         lowercase__   :       int				=	do_center_crop
         lowercase__   :       Union[str, Any]				=	crop_size
         lowercase__   :       int				=	do_rescale
         lowercase__   :       List[str]				=	rescale_factor
         lowercase__   :       Tuple				=	do_normalize
         lowercase__   :       str				=	image_mean if image_mean is not None else OPENAI_CLIP_MEAN
         lowercase__   :       Optional[Any]				=	image_std if image_std is not None else OPENAI_CLIP_STD
         lowercase__   :       List[Any]				=	do_convert_rgb





    def 				snake_case_    (				self						,       a						,       a						,       a = PILImageResampling.BICUBIC						,       a = None						,       **a						,       ):
         lowercase__   :       str				=	get_size_dict(a						,       default_to_square=a)
         if "shortest_edge" not in size:
              raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""")
         lowercase__   :       str				=	get_resize_output_image_size(a						,       size=size['shortest_edge']						,       default_to_square=a)
         return resize(a						,       size=a						,       resample=a						,       data_format=a						,       **a)





    def 				snake_case_    (				self						,       a						,       a						,       a = None						,       **a						,       ):
         lowercase__   :       List[str]				=	get_size_dict(a)
         if "height" not in size or "width" not in size:
              raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""")
         return center_crop(a						,       size=(size['height'], size['width'])						,       data_format=a						,       **a)





    def 				snake_case_    (				self						,       a						,       a						,       a = None						,       **a						,       ):
         return rescale(a						,       scale=a						,       data_format=a						,       **a)





    def 				snake_case_    (				self						,       a						,       a						,       a						,       a = None						,       **a						,       ):
         return normalize(a						,       mean=a						,       std=a						,       data_format=a						,       **a)





    def 				snake_case_    (				self						,       a						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = ChannelDimension.FIRST						,       **a						,       ):
         lowercase__   :       int				=	do_resize if do_resize is not None else self.do_resize
         lowercase__   :       Tuple				=	size if size is not None else self.size
         lowercase__   :       Union[str, Any]				=	get_size_dict(a						,       param_name='size'						,       default_to_square=a)
         lowercase__   :       Optional[Any]				=	resample if resample is not None else self.resample
         lowercase__   :       int				=	do_center_crop if do_center_crop is not None else self.do_center_crop
         lowercase__   :       List[Any]				=	crop_size if crop_size is not None else self.crop_size
         lowercase__   :       Union[str, Any]				=	get_size_dict(a						,       param_name='crop_size'						,       default_to_square=a)
         lowercase__   :       Dict				=	do_rescale if do_rescale is not None else self.do_rescale
         lowercase__   :       int				=	rescale_factor if rescale_factor is not None else self.rescale_factor
         lowercase__   :       List[str]				=	do_normalize if do_normalize is not None else self.do_normalize
         lowercase__   :       Optional[Any]				=	image_mean if image_mean is not None else self.image_mean
         lowercase__   :       List[str]				=	image_std if image_std is not None else self.image_std
         lowercase__   :       Any				=	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

         lowercase__   :       str				=	make_list_of_images(a)

         if not valid_images(a):
              raise ValueError(
                  'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
                  'torch.Tensor, tf.Tensor or jax.ndarray.')

         if do_resize and size is None:
              raise ValueError('Size must be specified if do_resize is True.')

         if do_center_crop and crop_size is None:
              raise ValueError('Crop size must be specified if do_center_crop is True.')

         if do_rescale and rescale_factor is None:
              raise ValueError('Rescale factor must be specified if do_rescale is True.')

         if do_normalize and (image_mean is None or image_std is None):
              raise ValueError('Image mean and std must be specified if do_normalize is True.')

         # PIL RGBA images are converted to RGB
         if do_convert_rgb:
              lowercase__   :       str				=	[convert_to_rgb(a) for image in images]

         # All transformations expect numpy arrays.
         lowercase__   :       Dict				=	[to_numpy_array(a) for image in images]

         if do_resize:
              lowercase__   :       Tuple				=	[self.resize(image=a						,       size=a						,       resample=a) for image in images]

         if do_center_crop:
              lowercase__   :       List[str]				=	[self.center_crop(image=a						,       size=a) for image in images]

         if do_rescale:
              lowercase__   :       str				=	[self.rescale(image=a						,       scale=a) for image in images]

         if do_normalize:
              lowercase__   :       Tuple				=	[self.normalize(image=a						,       mean=a						,       std=a) for image in images]

         lowercase__   :       Optional[int]				=	[to_channel_dimension_format(a						,       a) for image in images]

         lowercase__   :       Dict				=	{'pixel_values': images}
         return BatchFeature(data=a						,       tensor_type=a)

