


"""simple docstring"""




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




							def   __a   (     self:    int   ):
										__lowerCamelCase          =      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 			__snake_case   :




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




							def   __a   (     self:    int   ):
										__lowerCamelCase          =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

										__lowerCamelCase          =      self.get_config()

										return config, pixel_values, labels, pixel_labels




							def   __a   (     self:    int   ):
										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   __a   (     self:    Union[str, Any]     ,							A_:    int     ,							A_:    int     ,							A_:    Optional[Any]     ,							A_:    Any   ):
										__lowerCamelCase          =      MobileViTModel(config=A_   )
										model.to(A_   )
										model.eval()
										__lowerCamelCase          =      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   __a   (     self:    List[Any]     ,							A_:    Tuple     ,							A_:    int     ,							A_:    List[Any]     ,							A_:    Any   ):
										__lowerCamelCase          =      self.num_labels
										__lowerCamelCase          =      MobileViTForImageClassification(A_   )
										model.to(A_   )
										model.eval()
										__lowerCamelCase          =      model(A_     ,							labels=A_   )
										self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)   )




							def   __a   (     self:    Union[str, Any]     ,							A_:    int     ,							A_:    Union[str, Any]     ,							A_:    Union[str, Any]     ,							A_:    Any   ):
										__lowerCamelCase          =      self.num_labels
										__lowerCamelCase          =      MobileViTForSemanticSegmentation(A_   )
										model.to(A_   )
										model.eval()
										__lowerCamelCase          =      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,
										    )     ,							)
										__lowerCamelCase          =      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   __a   (     self:    int   ):
										__lowerCamelCase          =      self.prepare_config_and_inputs()
										__lowerCamelCase     ,__lowerCamelCase     ,__lowerCamelCase     ,__lowerCamelCase          =      config_and_inputs
										__lowerCamelCase          =      {"""pixel_values""": pixel_values}
										return config, inputs_dict




@require_torch
class 			__snake_case   (lowerCamelCase			,		lowerCamelCase			,		unittest.TestCase  ):
							__a					 =       (
							    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)
							__a					 =       (
							    {
							        '''feature-extraction''': MobileViTModel,
							        '''image-classification''': MobileViTForImageClassification,
							        '''image-segmentation''': MobileViTForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							__a					 =       False
							__a					 =       False
							__a					 =       False
							__a					 =       False




							def   __a   (     self:    int   ):
										__lowerCamelCase          =      MobileViTModelTester(self   )
										__lowerCamelCase          =      MobileViTConfigTester(self     ,							config_class=A_     ,							has_text_modality=A_   )




							def   __a   (     self:    Union[str, Any]   ):
										self.config_tester.run_common_tests()




							@unittest.skip(reason="""MobileViT does not use inputs_embeds"""   )
							def   __a   (     self:    int   ):
										pass




							@unittest.skip(reason="""MobileViT does not support input and output embeddings"""   )
							def   __a   (     self:    Optional[int]   ):
										pass




							@unittest.skip(reason="""MobileViT does not output attentions"""   )
							def   __a   (     self:    List[Any]   ):
										pass




							def   __a   (     self:    Union[str, Any]   ):
										__lowerCamelCase     ,__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs_for_common()

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

													__lowerCamelCase          =      ["""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   __a   (     self:    int   ):
										pass




							def   __a   (     self:    str   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*A_   )




							def   __a   (     self:    Dict   ):
										def check_hidden_states_output(A_:    List[Any]     ,							A_:    Optional[int]     ,							A_:    Union[str, Any]   ):
													__lowerCamelCase          =      model_class(A_   )
													model.to(A_   )
													model.eval()

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

													__lowerCamelCase          =      outputs.hidden_states

													__lowerCamelCase          =      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.
													__lowerCamelCase          =      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   )

										__lowerCamelCase     ,__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													__lowerCamelCase          =      True
													check_hidden_states_output(A_     ,							A_     ,							A_   )

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													__lowerCamelCase          =      True

													check_hidden_states_output(A_     ,							A_     ,							A_   )




							def   __a   (     self:    str   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*A_   )




							def   __a   (     self:    str   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*A_   )




							@slow
							def   __a   (     self:    Dict   ):
										for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__lowerCamelCase          =      MobileViTModel.from_pretrained(A_   )
													self.assertIsNotNone(A_   )





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




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




							@cached_property
							def   __a   (     self:    List[str]   ):
										return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""   ) if is_vision_available() else None




							@slow
							def   __a   (     self:    Any   ):
										__lowerCamelCase          =      MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""   ).to(A_   )

										__lowerCamelCase          =      self.default_image_processor
										__lowerCamelCase          =      prepare_img()
										__lowerCamelCase          =      image_processor(images=A_     ,							return_tensors="""pt"""   ).to(A_   )

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

										# verify the logits
										__lowerCamelCase          =      torch.Size((1, 10_00)   )
										self.assertEqual(outputs.logits.shape     ,							A_   )

										__lowerCamelCase          =      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   __a   (     self:    Tuple   ):
										__lowerCamelCase          =      MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""   )
										__lowerCamelCase          =      model.to(A_   )

										__lowerCamelCase          =      MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""   )

										__lowerCamelCase          =      prepare_img()
										__lowerCamelCase          =      image_processor(images=A_     ,							return_tensors="""pt"""   ).to(A_   )

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

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

										__lowerCamelCase          =      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   __a   (     self:    Dict   ):
										__lowerCamelCase          =      MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""   )
										__lowerCamelCase          =      model.to(A_   )

										__lowerCamelCase          =      MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""   )

										__lowerCamelCase          =      prepare_img()
										__lowerCamelCase          =      image_processor(images=A_     ,							return_tensors="""pt"""   ).to(A_   )

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

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

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

										__lowerCamelCase          =      image_processor.post_process_semantic_segmentation(outputs=A_   )
										__lowerCamelCase          =      torch.Size((32, 32)   )
										self.assertEqual(segmentation[0].shape     ,							A_   )








"""simple docstring"""




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 			__snake_case   (lowerCamelCase  ):
							__a					 =       ['''image_processor''', '''tokenizer''']
							__a					 =       '''LayoutLMv2ImageProcessor'''
							__a					 =       ('''LayoutXLMTokenizer''', '''LayoutXLMTokenizerFast''')




							def __init__(     self:    Any     ,							A_:    Optional[Any]=None     ,							A_:    Dict=None     ,							**A_:    Any   ):
										if "feature_extractor" in kwargs:
													warnings.warn(
													    """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
													    """ instead."""     ,							A_     ,							)
													__lowerCamelCase          =      kwargs.pop("""feature_extractor"""   )

										__lowerCamelCase          =      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:    List[str]     ,							A_:    Any     ,							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_:    Any     ,							):
										# 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
										__lowerCamelCase          =      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_   ):
																__lowerCamelCase          =      [text]  # add batch dimension (as the image processor always adds a batch dimension)
													__lowerCamelCase          =      features["""words"""]

										__lowerCamelCase          =      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
										__lowerCamelCase          =      features.pop("""pixel_values"""   )
										if return_overflowing_tokens is True:
													__lowerCamelCase          =      self.get_overflowing_images(A_     ,							encoded_inputs["""overflow_to_sample_mapping"""]   )
										__lowerCamelCase          =      images

										return encoded_inputs




							def   __a   (     self:    Optional[Any]     ,							A_:    Any     ,							A_:    Tuple   ):
										# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
										__lowerCamelCase          =      []
										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   __a   (     self:    Optional[Any]     ,							*A_:    str     ,							**A_:    Dict   ):
										return self.tokenizer.batch_decode(*A_     ,							**A_   )




							def   __a   (     self:    Union[str, Any]     ,							*A_:    Optional[Any]     ,							**A_:    Tuple   ):
										return self.tokenizer.decode(*A_     ,							**A_   )




							@property
							def   __a   (     self:    Union[str, Any]   ):
										return ["input_ids", "bbox", "attention_mask", "image"]




							@property
							def   __a   (     self:    Optional[Any]   ):
										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   __a   (     self:    List[Any]   ):
										warnings.warn(
										    """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""     ,							A_     ,							)
										return self.image_processor




