
import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
   from transformers.models.mobilevitva.modeling_mobilevitva import (
       MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
       make_divisible,
   )


if is_vision_available():
   from PIL import Image

   from transformers import MobileViTImageProcessor







class 					lowerCamelCase		(  lowerCAmelCase_  ):





     def 		UpperCAmelCase(self				:   Optional[Any]       )						->						int:
         snake_case								= self.config_class(**self.inputs_dict       )
         self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE    ,   "width_multiplier"       )       )







class 					lowerCamelCase		:





     def __init__(self				:   str    ,   _A				:   Tuple    ,   _A				:   List[str]=1_3    ,   _A				:   Optional[Any]=6_4    ,   _A				:   Optional[Any]=2    ,   _A				:   Tuple=3    ,   _A				:   Dict="swish"    ,   _A				:   str=3    ,   _A				:   Dict=3_2    ,   _A				:   Tuple=0.1    ,   _A				:   Dict=0.02    ,   _A				:   Optional[int]=True    ,   _A				:   Dict=True    ,   _A				:   Union[str, Any]=1_0    ,   _A				:   Optional[int]=None    ,   _A				:   Any=0.25    ,   _A				:   int=0.0    ,   _A				:   str=0.0    ,   )						->						str:
         snake_case								= parent
         snake_case								= batch_size
         snake_case								= image_size
         snake_case								= patch_size
         snake_case								= num_channels
         snake_case								= make_divisible(5_1_2 * width_multiplier    ,   divisor=8       )
         snake_case								= hidden_act
         snake_case								= conv_kernel_size
         snake_case								= output_stride
         snake_case								= classifier_dropout_prob
         snake_case								= use_labels
         snake_case								= is_training
         snake_case								= num_labels
         snake_case								= initializer_range
         snake_case								= scope
         snake_case								= width_multiplier
         snake_case								= ffn_dropout
         snake_case								= attn_dropout





     def 		UpperCAmelCase(self				:   List[Any]       )						->						Optional[int]:
         snake_case								= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

         snake_case								= None
         snake_case								= None
         if self.use_labels:
             snake_case								= ids_tensor([self.batch_size]    ,   self.num_labels       )
             snake_case								= ids_tensor([self.batch_size, self.image_size, self.image_size]    ,   self.num_labels       )

         snake_case								= self.get_config()

         return config, pixel_values, labels, pixel_labels





     def 		UpperCAmelCase(self				:   int       )						->						Dict:
         return MobileViTVaConfig(
             image_size=self.image_size    ,   patch_size=self.patch_size    ,   num_channels=self.num_channels    ,   hidden_act=self.hidden_act    ,   conv_kernel_size=self.conv_kernel_size    ,   output_stride=self.output_stride    ,   classifier_dropout_prob=self.classifier_dropout_prob    ,   initializer_range=self.initializer_range    ,   width_multiplier=self.width_multiplier    ,   ffn_dropout=self.ffn_dropout_prob    ,   attn_dropout=self.attn_dropout_prob    ,   )





     def 		UpperCAmelCase(self				:   Tuple    ,   _A				:   Union[str, Any]    ,   _A				:   Union[str, Any]    ,   _A				:   Optional[int]    ,   _A				:   str       )						->						Tuple:
         snake_case								= MobileViTVaModel(config=__SCREAMING_SNAKE_CASE       )
         model.to(__SCREAMING_SNAKE_CASE       )
         model.eval()
         snake_case								= model(__SCREAMING_SNAKE_CASE       )
         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				:   Tuple    ,   _A				:   Optional[int]    ,   _A				:   Any    ,   _A				:   Any    ,   _A				:   List[str]       )						->						Optional[Any]:
         snake_case								= self.num_labels
         snake_case								= MobileViTVaForImageClassification(__SCREAMING_SNAKE_CASE       )
         model.to(__SCREAMING_SNAKE_CASE       )
         model.eval()
         snake_case								= model(__SCREAMING_SNAKE_CASE    ,   labels=__SCREAMING_SNAKE_CASE       )
         self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.num_labels)       )





     def 		UpperCAmelCase(self				:   int    ,   _A				:   Any    ,   _A				:   List[str]    ,   _A				:   str    ,   _A				:   Optional[int]       )						->						str:
         snake_case								= self.num_labels
         snake_case								= MobileViTVaForSemanticSegmentation(__SCREAMING_SNAKE_CASE       )
         model.to(__SCREAMING_SNAKE_CASE       )
         model.eval()
         snake_case								= model(__SCREAMING_SNAKE_CASE       )
         self.parent.assertEqual(
             result.logits.shape    ,   (
                 self.batch_size,
                 self.num_labels,
                 self.image_size // self.output_stride,
                 self.image_size // self.output_stride,
             )    ,   )
         snake_case								= model(__SCREAMING_SNAKE_CASE    ,   labels=__SCREAMING_SNAKE_CASE       )
         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				:   Optional[int]       )						->						int:
         snake_case								= self.prepare_config_and_inputs()
         snake_case					,							snake_case					,							snake_case					,							snake_case								= config_and_inputs
         snake_case								= {"pixel_values": pixel_values}
         return config, inputs_dict







@require_torch
class 					lowerCamelCase		(  lowerCAmelCase_							,			lowerCAmelCase_							,			unittest.TestCase  ):
     UpperCAmelCase__    :							Optional[int]									=		(
         (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )

     UpperCAmelCase__    :							Optional[Any]									=		(
         {
             """feature-extraction""": MobileViTVaModel,
             """image-classification""": MobileViTVaForImageClassification,
             """image-segmentation""": MobileViTVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     UpperCAmelCase__    :							str									=		False
     UpperCAmelCase__    :							Tuple									=		False
     UpperCAmelCase__    :							Tuple									=		False
     UpperCAmelCase__    :							Union[str, Any]									=		False





     def 		UpperCAmelCase(self				:   Dict       )						->						Dict:
         snake_case								= MobileViTVaModelTester(self       )
         snake_case								= MobileViTVaConfigTester(self    ,   config_class=__SCREAMING_SNAKE_CASE    ,   has_text_modality=__SCREAMING_SNAKE_CASE       )





     def 		UpperCAmelCase(self				:   List[Any]       )						->						Dict:
         self.config_tester.run_common_tests()





     @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"       )
     def 		UpperCAmelCase(self				:   Optional[int]       )						->						Optional[int]:
         pass





     @unittest.skip(reason="MobileViTV2 does not support input and output embeddings"       )
     def 		UpperCAmelCase(self				:   Tuple       )						->						Dict:
         pass





     @unittest.skip(reason="MobileViTV2 does not output attentions"       )
     def 		UpperCAmelCase(self				:   str       )						->						Any:
         pass





     @require_torch_multi_gpu
     @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."       )
     def 		UpperCAmelCase(self				:   Tuple       )						->						Any:
         pass





     @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."       )
     def 		UpperCAmelCase(self				:   Tuple       )						->						Optional[Any]:
         pass





     def 		UpperCAmelCase(self				:   List[Any]       )						->						List[str]:
         snake_case					,							snake_case								= self.model_tester.prepare_config_and_inputs_for_common()

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

             snake_case								= ["pixel_values"]
             self.assertListEqual(arg_names[:1]    ,   __SCREAMING_SNAKE_CASE       )





     def 		UpperCAmelCase(self				:   List[str]       )						->						Any:
         snake_case								= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE       )





     def 		UpperCAmelCase(self				:   int       )						->						List[Any]:

         def check_hidden_states_output(_A				:   str    ,   _A				:   Any    ,   _A				:   Tuple       ):
             snake_case								= model_class(__SCREAMING_SNAKE_CASE       )
             model.to(__SCREAMING_SNAKE_CASE       )
             model.eval()

             with torch.no_grad():
                 snake_case								= model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE    ,   __SCREAMING_SNAKE_CASE       )       )

             snake_case								= outputs.hidden_states

             snake_case								= 5
             self.assertEqual(len(__SCREAMING_SNAKE_CASE       )    ,   __SCREAMING_SNAKE_CASE       )

             # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
             # with the width and height being successively divided by 2.
             snake_case								= 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       )

         snake_case					,							snake_case								= self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             snake_case								= 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"]
             snake_case								= True

             check_hidden_states_output(__SCREAMING_SNAKE_CASE    ,   __SCREAMING_SNAKE_CASE    ,   __SCREAMING_SNAKE_CASE       )





     def 		UpperCAmelCase(self				:   int       )						->						Tuple:
         snake_case								= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE       )





     def 		UpperCAmelCase(self				:   List[str]       )						->						Tuple:
         snake_case								= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE       )





     @slow
     def 		UpperCAmelCase(self				:   Optional[Any]       )						->						List[str]:

         for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             snake_case								= MobileViTVaModel.from_pretrained(__SCREAMING_SNAKE_CASE       )
             self.assertIsNotNone(__SCREAMING_SNAKE_CASE       )



def 						lowercase_      (       ):
    """simple docstring"""

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







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





     @cached_property
     def 		UpperCAmelCase(self				:   int       )						->						Dict:
         return (
             MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"       )
             if is_vision_available()
             else None
         )





     @slow
     def 		UpperCAmelCase(self				:   Optional[int]       )						->						Union[str, Any]:
         snake_case								= MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"       ).to(
             __SCREAMING_SNAKE_CASE       )

         snake_case								= self.default_image_processor
         snake_case								= prepare_img()
         snake_case								= image_processor(images=__SCREAMING_SNAKE_CASE    ,   return_tensors="pt"       ).to(__SCREAMING_SNAKE_CASE       )

         # forward pass
         with torch.no_grad():
             snake_case								= model(**__SCREAMING_SNAKE_CASE       )

         # verify the logits
         snake_case								= torch.Size((1, 1_0_0_0)       )
         self.assertEqual(outputs.logits.shape    ,   __SCREAMING_SNAKE_CASE       )

         snake_case								= torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01]       ).to(__SCREAMING_SNAKE_CASE       )

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





     @slow
     def 		UpperCAmelCase(self				:   Optional[Any]       )						->						Optional[int]:
         snake_case								= MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"       )
         snake_case								= model.to(__SCREAMING_SNAKE_CASE       )

         snake_case								= MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"       )

         snake_case								= prepare_img()
         snake_case								= image_processor(images=__SCREAMING_SNAKE_CASE    ,   return_tensors="pt"       ).to(__SCREAMING_SNAKE_CASE       )

         # forward pass
         with torch.no_grad():
             snake_case								= model(**__SCREAMING_SNAKE_CASE       )
         snake_case								= outputs.logits

         # verify the logits
         snake_case								= torch.Size((1, 2_1, 3_2, 3_2)       )
         self.assertEqual(logits.shape    ,   __SCREAMING_SNAKE_CASE       )

         snake_case								= torch.tensor(
             [
                 [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
                 [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
                 [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
             ]    ,   device=__SCREAMING_SNAKE_CASE    ,   )

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





     @slow
     def 		UpperCAmelCase(self				:   str       )						->						Dict:
         snake_case								= MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"       )
         snake_case								= model.to(__SCREAMING_SNAKE_CASE       )

         snake_case								= MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"       )

         snake_case								= prepare_img()
         snake_case								= image_processor(images=__SCREAMING_SNAKE_CASE    ,   return_tensors="pt"       ).to(__SCREAMING_SNAKE_CASE       )

         # forward pass
         with torch.no_grad():
             snake_case								= model(**__SCREAMING_SNAKE_CASE       )

         snake_case								= outputs.logits.detach().cpu()

         snake_case								= image_processor.post_process_semantic_segmentation(outputs=__SCREAMING_SNAKE_CASE    ,   target_sizes=[(5_0, 6_0)]       )
         snake_case								= torch.Size((5_0, 6_0)       )
         self.assertEqual(segmentation[0].shape    ,   __SCREAMING_SNAKE_CASE       )

         snake_case								= image_processor.post_process_semantic_segmentation(outputs=__SCREAMING_SNAKE_CASE       )
         snake_case								= torch.Size((3_2, 3_2)       )
         self.assertEqual(segmentation[0].shape    ,   __SCREAMING_SNAKE_CASE       )



import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							Dict									=		["image_processor", "tokenizer"]
     UpperCAmelCase__    :							Dict									=		"LayoutLMv2ImageProcessor"
     UpperCAmelCase__    :							Optional[Any]									=		("LayoutXLMTokenizer", "LayoutXLMTokenizerFast")





     def __init__(self				:   str    ,   _A				:   Any=None    ,   _A				:   Tuple=None    ,   **_A				:   Optional[Any]       )						->						Optional[int]:
         if "feature_extractor" in kwargs:
             warnings.warn(
                 "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                 " instead."    ,   _A    ,   )
             snake_case								= kwargs.pop("feature_extractor"       )

         snake_case								= image_processor if image_processor is not None else feature_extractor
         if image_processor is None:
             raise ValueError("You need to specify an `image_processor`."       )
         if tokenizer is None:
             raise ValueError("You need to specify a `tokenizer`."       )

         super().__init__(_A    ,   _A       )





     def __call__(self				:   int    ,   _A				:   List[str]    ,   _A				:   Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None    ,   _A				:   Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None    ,   _A				:   Union[List[List[int]], List[List[List[int]]]] = None    ,   _A				:   Optional[Union[List[int], List[List[int]]]] = None    ,   _A				:   bool = True    ,   _A				:   Union[bool, str, PaddingStrategy] = False    ,   _A				:   Union[bool, str, TruncationStrategy] = None    ,   _A				:   Optional[int] = None    ,   _A				:   int = 0    ,   _A				:   Optional[int] = None    ,   _A				:   Optional[bool] = None    ,   _A				:   Optional[bool] = None    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = True    ,   _A				:   Optional[Union[str, TensorType]] = None    ,   **_A				:   Dict    ,   )						->						BatchEncoding:
         # verify input
         if self.image_processor.apply_ocr and (boxes is not None):
             raise ValueError(
                 "You cannot provide bounding boxes "
                 "if you initialized the image processor with apply_ocr set to True."       )

         if self.image_processor.apply_ocr and (word_labels is not None):
             raise ValueError(
                 "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."       )

         if return_overflowing_tokens is True and return_offsets_mapping is False:
             raise ValueError("You cannot return overflowing tokens without returning the offsets mapping."       )

         # first, apply the image processor
         snake_case								= self.image_processor(images=_A    ,   return_tensors=_A       )

         # second, apply the tokenizer
         if text is not None and self.image_processor.apply_ocr and text_pair is None:
             if isinstance(_A    ,   _A       ):
                 snake_case								= [text]  # add batch dimension (as the image processor always adds a batch dimension)
             snake_case								= features["words"]

         snake_case								= self.tokenizer(
             text=text if text is not None else features["words"]    ,   text_pair=text_pair if text_pair is not None else None    ,   boxes=boxes if boxes is not None else features["boxes"]    ,   word_labels=_A    ,   add_special_tokens=_A    ,   padding=_A    ,   truncation=_A    ,   max_length=_A    ,   stride=_A    ,   pad_to_multiple_of=_A    ,   return_token_type_ids=_A    ,   return_attention_mask=_A    ,   return_overflowing_tokens=_A    ,   return_special_tokens_mask=_A    ,   return_offsets_mapping=_A    ,   return_length=_A    ,   verbose=_A    ,   return_tensors=_A    ,   **_A    ,   )

         # add pixel values
         snake_case								= features.pop("pixel_values"       )
         if return_overflowing_tokens is True:
             snake_case								= self.get_overflowing_images(_A    ,   encoded_inputs["overflow_to_sample_mapping"]       )
         snake_case								= images

         return encoded_inputs





     def 		UpperCAmelCase(self				:   Dict    ,   _A				:   Dict    ,   _A				:   List[str]       )						->						Optional[int]:
         # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
         snake_case								= []
         for sample_idx in overflow_to_sample_mapping:
             images_with_overflow.append(images[sample_idx]       )

         if len(_A       ) != len(_A       ):
             raise ValueError(
                 "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
                 f' {len(_A       )} and {len(_A       )}'       )

         return images_with_overflow





     def 		UpperCAmelCase(self				:   Tuple    ,   *_A				:   int    ,   **_A				:   Dict       )						->						str:
         return self.tokenizer.batch_decode(*_A    ,   **_A       )





     def 		UpperCAmelCase(self				:   str    ,   *_A				:   List[Any]    ,   **_A				:   List[Any]       )						->						Optional[Any]:
         return self.tokenizer.decode(*_A    ,   **_A       )





     @property
     def 		UpperCAmelCase(self				:   Tuple       )						->						Optional[int]:
         return ["input_ids", "bbox", "attention_mask", "image"]





     @property
     def 		UpperCAmelCase(self				:   List[Any]       )						->						int:
         warnings.warn(
             "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."    ,   _A    ,   )
         return self.image_processor_class





     @property
     def 		UpperCAmelCase(self				:   Dict       )						->						Union[str, Any]:
         warnings.warn(
             "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."    ,   _A    ,   )
         return self.image_processor

