

'''simple docstring'''


import io
import math
from typing import Dict, Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    get_image_size,
    infer_channel_dimension_format,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_vision_available, logging
from ...utils.import_utils import requires_backends


if is_vision_available():
					import textwrap

					from PIL import Image, ImageDraw, ImageFont

if is_torch_available():
					import torch

					from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
					lowerCAmelCase__						:       Union[str, Any]										=						False


lowerCAmelCase__						:       Any										=						logging.get_logger(__name__)
lowerCAmelCase__						:       str										=						"""ybelkada/fonts"""




def 	_a       (				):

		"""simple docstring"""

		if is_torch_available() and not is_torch_greater_or_equal_than_1_11:
				raise ImportError(
				    F"""You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use """
				    '''Pix2StructImageProcessor. Please upgrade torch.'''     )




def 	_a       (				__lowerCAmelCase		:      Union[str, Any]   ,							__lowerCAmelCase		:      Tuple   ,							__lowerCAmelCase		:      Optional[int]     ):

		"""simple docstring"""

		requires_backends(__lowerCAmelCase   ,							['''torch''']     )
		_check_torch_version()

		snake_case__						:       List[Any]       						=  image_tensor.unsqueeze(0     )
		snake_case__						:       List[str]       						=  torch.nn.functional.unfold(__lowerCAmelCase   ,							(patch_height, patch_width)   ,							stride=(patch_height, patch_width)     )
		snake_case__						:       Any       						=  patches.reshape(image_tensor.size(0     )   ,							image_tensor.size(1     )   ,							__lowerCAmelCase   ,							__lowerCAmelCase   ,							-1     )
		snake_case__						:       Dict       						=  patches.permute(0   ,							4   ,							2   ,							3   ,							1     ).reshape(
		    image_tensor.size(2     ) // patch_height   ,							image_tensor.size(3     ) // patch_width   ,							image_tensor.size(1     ) * patch_height * patch_width   ,							)
		return patches.unsqueeze(0     )




def 	_a       (				__lowerCAmelCase		:      str   ,							__lowerCAmelCase		:      int = 36   ,							__lowerCAmelCase		:      str = "black"   ,							__lowerCAmelCase		:      str = "white"   ,							__lowerCAmelCase		:      int = 5   ,							__lowerCAmelCase		:      int = 5   ,							__lowerCAmelCase		:      int = 5   ,							__lowerCAmelCase		:      int = 5   ,							__lowerCAmelCase		:      Optional[bytes] = None   ,							__lowerCAmelCase		:      Optional[str] = None   ,							):

		"""simple docstring"""

		requires_backends(__lowerCAmelCase   ,							'''vision'''     )
		# Add new lines so that each line is no more than 80 characters.

		snake_case__						:       Tuple       						=  textwrap.TextWrapper(width=80     )
		snake_case__						:       int       						=  wrapper.wrap(text=__lowerCAmelCase     )
		snake_case__						:       Optional[int]       						=  '''\n'''.join(__lowerCAmelCase     )

		if font_bytes is not None and font_path is None:
				snake_case__						:       str       						=  io.BytesIO(__lowerCAmelCase     )
		elif font_path is not None:
				snake_case__						:       str       						=  font_path
		else:
				snake_case__						:       Any       						=  hf_hub_download(__lowerCAmelCase   ,							'''Arial.TTF'''     )
		snake_case__						:       Optional[Any]       						=  ImageFont.truetype(__lowerCAmelCase   ,							encoding='''UTF-8'''   ,							size=__lowerCAmelCase     )

		# Use a temporary canvas to determine the width and height in pixels when
		# rendering the text.
		snake_case__						:       Tuple       						=  ImageDraw.Draw(Image.new('''RGB'''   ,							(1, 1)   ,							__lowerCAmelCase     )     )
		snake_case__						,       snake_case__						,       snake_case__						,       snake_case__						:       Dict       						=  temp_draw.textbbox((0, 0)   ,							__lowerCAmelCase   ,							__lowerCAmelCase     )

		# Create the actual image with a bit of padding around the text.
		snake_case__						:       Optional[int]       						=  text_width + left_padding + right_padding
		snake_case__						:       str       						=  text_height + top_padding + bottom_padding
		snake_case__						:       Tuple       						=  Image.new('''RGB'''   ,							(image_width, image_height)   ,							__lowerCAmelCase     )
		snake_case__						:       Union[str, Any]       						=  ImageDraw.Draw(__lowerCAmelCase     )
		draw.text(xy=(left_padding, top_padding)   ,							text=__lowerCAmelCase   ,							fill=__lowerCAmelCase   ,							font=__lowerCAmelCase     )
		return image




def 	_a       (				__lowerCAmelCase		:      np.ndarray   ,							__lowerCAmelCase		:      str   ,							**__lowerCAmelCase		:      List[str]     ):

		"""simple docstring"""

		requires_backends(__lowerCAmelCase   ,							'''vision'''     )

		# Convert to PIL image if necessary
		snake_case__						:       str       						=  to_pil_image(__lowerCAmelCase     )

		snake_case__						:       int       						=  render_text(__lowerCAmelCase   ,							**__lowerCAmelCase     )
		snake_case__						:       Optional[int]       						=  max(header_image.width   ,							image.width     )

		snake_case__						:       Optional[int]       						=  int(image.height * (new_width / image.width)     )
		snake_case__						:       int       						=  int(header_image.height * (new_width / header_image.width)     )

		snake_case__						:       Dict       						=  Image.new('''RGB'''   ,							(new_width, new_height + new_header_height)   ,							'''white'''     )
		new_image.paste(header_image.resize((new_width, new_header_height)     )   ,							(0, 0)     )
		new_image.paste(image.resize((new_width, new_height)     )   ,							(0, new_header_height)     )

		# Convert back to the original framework if necessary
		snake_case__						:       Tuple       						=  to_numpy_array(__lowerCAmelCase     )

		if infer_channel_dimension_format(__lowerCAmelCase     ) == ChannelDimension.LAST:
				snake_case__						:       Tuple       						=  to_channel_dimension_format(__lowerCAmelCase   ,							ChannelDimension.LAST     )

		return new_image





class     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




						__UpperCAmelCase			     =    ["""flattened_patches"""]







						def __init__(							self					:      List[str]			,			snake_case_					:      bool = True			,			snake_case_					:      bool = True			,			snake_case_					:      Dict[str, int] = None			,			snake_case_					:      int = 2_0_4_8			,			snake_case_					:      bool = False			,			**snake_case_					:      Union[str, Any]			,			):



								'''simple docstring'''



								super().__init__(**snake_case_  )
								snake_case__						:       Optional[int]       						=  patch_size if patch_size is not None else {'''height''': 1_6, '''width''': 1_6}
								snake_case__						:       Union[str, Any]       						=  do_normalize
								snake_case__						:       Optional[Any]       						=  do_convert_rgb
								snake_case__						:       Any       						=  max_patches
								snake_case__						:       Any       						=  is_vqa







						def       __magic_name__							(							self					:      Any			,			snake_case_					:      np.ndarray			,			snake_case_					:      int			,			snake_case_					:      dict			,			**snake_case_					:      Optional[int]  ):



								'''simple docstring'''



								requires_backends(self.extract_flattened_patches			,			'''torch'''  )
								_check_torch_version()

								# convert to torch
								snake_case__						:       Any       						=  to_channel_dimension_format(snake_case_			,			ChannelDimension.FIRST  )
								snake_case__						:       List[str]       						=  torch.from_numpy(snake_case_  )

								snake_case__						,       snake_case__						:       List[Any]       						=  patch_size['''height'''], patch_size['''width''']
								snake_case__						,       snake_case__						:       List[Any]       						=  get_image_size(snake_case_  )

								# maximize scale s.t.
								snake_case__						:       str       						=  math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width)  )
								snake_case__						:       Tuple       						=  max(min(math.floor(scale * image_height / patch_height  )			,			snake_case_  )			,			1  )
								snake_case__						:       Optional[int]       						=  max(min(math.floor(scale * image_width / patch_width  )			,			snake_case_  )			,			1  )
								snake_case__						:       Optional[Any]       						=  max(num_feasible_rows * patch_height			,			1  )
								snake_case__						:       Optional[Any]       						=  max(num_feasible_cols * patch_width			,			1  )

								snake_case__						:       int       						=  torch.nn.functional.interpolate(
								    image.unsqueeze(0  )			,			size=(resized_height, resized_width)			,			mode='''bilinear'''			,			align_corners=snake_case_			,			antialias=snake_case_			,			).squeeze(0  )

								# [1, rows, columns, patch_height * patch_width * image_channels]
								snake_case__						:       Dict       						=  torch_extract_patches(snake_case_			,			snake_case_			,			snake_case_  )

								snake_case__						:       List[Any]       						=  patches.shape
								snake_case__						:       int       						=  patches_shape[1]
								snake_case__						:       str       						=  patches_shape[2]
								snake_case__						:       Any       						=  patches_shape[3]

								# [rows * columns, patch_height * patch_width * image_channels]
								snake_case__						:       List[Any]       						=  patches.reshape([rows * columns, depth]  )

								# [rows * columns, 1]
								snake_case__						:       int       						=  torch.arange(snake_case_  ).reshape([rows, 1]  ).repeat(1			,			snake_case_  ).reshape([rows * columns, 1]  )
								snake_case__						:       str       						=  torch.arange(snake_case_  ).reshape([1, columns]  ).repeat(snake_case_			,			1  ).reshape([rows * columns, 1]  )

								# Offset by 1 so the ids do not contain zeros, which represent padding.
								row_ids += 1
								col_ids += 1

								# Prepare additional patch features.
								# [rows * columns, 1]
								snake_case__						:       Dict       						=  row_ids.to(torch.floataa  )
								snake_case__						:       List[Any]       						=  col_ids.to(torch.floataa  )

								# [rows * columns, 2 + patch_height * patch_width * image_channels]
								snake_case__						:       int       						=  torch.cat([row_ids, col_ids, patches]			,			-1  )

								# [max_patches, 2 + patch_height * patch_width * image_channels]
								snake_case__						:       Any       						=  torch.nn.functional.pad(snake_case_			,			[0, 0, 0, max_patches - (rows * columns)]  ).float()

								snake_case__						:       List[str]       						=  to_numpy_array(snake_case_  )

								return result







						def       __magic_name__							(							self					:      Tuple			,			snake_case_					:      np.ndarray			,			snake_case_					:      Optional[Union[str, ChannelDimension]] = None			,			**snake_case_					:      Optional[int]  ):



								'''simple docstring'''



								if image.dtype == np.uinta:
										snake_case__						:       Any       						=  image.astype(np.floataa  )

								# take mean across the whole `image`
								snake_case__						:       Union[str, Any]       						=  np.mean(snake_case_  )
								snake_case__						:       Optional[Any]       						=  np.std(snake_case_  )
								snake_case__						:       Optional[Any]       						=  max(snake_case_			,			1.0 / math.sqrt(np.prod(image.shape  )  )  )

								return normalize(snake_case_			,			mean=snake_case_			,			std=snake_case_			,			**snake_case_  )







						def       __magic_name__							(							self					:      Tuple			,			snake_case_					:      ImageInput			,			snake_case_					:      Optional[str] = None			,			snake_case_					:      bool = None			,			snake_case_					:      Optional[bool] = None			,			snake_case_					:      Optional[int] = None			,			snake_case_					:      Optional[Dict[str, int]] = None			,			snake_case_					:      Optional[Union[str, TensorType]] = None			,			snake_case_					:      ChannelDimension = ChannelDimension.FIRST			,			**snake_case_					:      Union[str, Any]			,			):



								'''simple docstring'''



								snake_case__						:       Dict       						=  do_normalize if do_normalize is not None else self.do_normalize
								snake_case__						:       List[Any]       						=  do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
								snake_case__						:       int       						=  patch_size if patch_size is not None else self.patch_size
								snake_case__						:       Optional[Any]       						=  max_patches if max_patches is not None else self.max_patches
								snake_case__						:       List[str]       						=  self.is_vqa

								if kwargs.get('''data_format'''			,			snake_case_  ) is not None:
										raise ValueError('''data_format is not an accepted input as the outputs are '''  )

								snake_case__						:       Tuple       						=  make_list_of_images(snake_case_  )

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

								# PIL RGBA images are converted to RGB
								if do_convert_rgb:
										snake_case__						:       int       						=  [convert_to_rgb(snake_case_  ) for image in images]

								# All transformations expect numpy arrays.
								snake_case__						:       Optional[Any]       						=  [to_numpy_array(snake_case_  ) for image in images]

								if is_vqa:
										if header_text is None:
												raise ValueError('''A header text must be provided for VQA models.'''  )
										snake_case__						:       Optional[Any]       						=  kwargs.pop('''font_bytes'''			,			snake_case_  )
										snake_case__						:       List[Any]       						=  kwargs.pop('''font_path'''			,			snake_case_  )

										if isinstance(snake_case_			,			snake_case_  ):
												snake_case__						:       Optional[int]       						=  [header_text] * len(snake_case_  )

										snake_case__						:       List[str]       						=  [
										    render_header(snake_case_			,			header_text[i]			,			font_bytes=snake_case_			,			font_path=snake_case_  )
										    for i, image in enumerate(snake_case_  )
										]

								if do_normalize:
										snake_case__						:       List[str]       						=  [self.normalize(image=snake_case_  ) for image in images]

								# convert to torch tensor and permute
								snake_case__						:       Union[str, Any]       						=  [
								    self.extract_flattened_patches(image=snake_case_			,			max_patches=snake_case_			,			patch_size=snake_case_  )
								    for image in images
								]

								# create attention mask in numpy
								snake_case__						:       Tuple       						=  [(image.sum(axis=-1  ) != 0).astype(np.floataa  ) for image in images]

								snake_case__						:       List[str]       						=  BatchFeature(
								    data={'''flattened_patches''': images, '''attention_mask''': attention_masks}			,			tensor_type=snake_case_  )

								return encoded_outputs






'''simple docstring'''


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






						"""simple docstring"""




						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



								snake_case__						:       str       						=  self.config_class(**self.inputs_dict  )
								self.parent.assertTrue(hasattr(snake_case_			,			'''width_multiplier'''  )  )





class     a			:






						"""simple docstring"""




						def __init__(							self					:      List[str]			,			snake_case_					:      Optional[int]			,			snake_case_					:      Dict=1_3			,			snake_case_					:      Any=6_4			,			snake_case_					:      Dict=2			,			snake_case_					:      Optional[int]=3			,			snake_case_					:      str="swish"			,			snake_case_					:      str=3			,			snake_case_					:      Union[str, Any]=3_2			,			snake_case_					:      Optional[Any]=0.1			,			snake_case_					:      Any=0.0_2			,			snake_case_					:      int=True			,			snake_case_					:      Tuple=True			,			snake_case_					:      Dict=1_0			,			snake_case_					:      Optional[int]=None			,			snake_case_					:      str=0.2_5			,			snake_case_					:      List[Any]=0.0			,			snake_case_					:      Optional[Any]=0.0			,			):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  parent
								snake_case__						:       Dict       						=  batch_size
								snake_case__						:       Dict       						=  image_size
								snake_case__						:       Tuple       						=  patch_size
								snake_case__						:       Tuple       						=  num_channels
								snake_case__						:       Tuple       						=  make_divisible(5_1_2 * width_multiplier			,			divisor=8  )
								snake_case__						:       Optional[int]       						=  hidden_act
								snake_case__						:       int       						=  conv_kernel_size
								snake_case__						:       Optional[int]       						=  output_stride
								snake_case__						:       List[Any]       						=  classifier_dropout_prob
								snake_case__						:       int       						=  use_labels
								snake_case__						:       Optional[Any]       						=  is_training
								snake_case__						:       int       						=  num_labels
								snake_case__						:       str       						=  initializer_range
								snake_case__						:       Dict       						=  scope
								snake_case__						:       Tuple       						=  width_multiplier
								snake_case__						:       Optional[Any]       						=  ffn_dropout
								snake_case__						:       Dict       						=  attn_dropout







						def       __magic_name__							(							self					:      str  ):



								'''simple docstring'''



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

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

								snake_case__						:       Optional[int]       						=  self.get_config()

								return config, pixel_values, labels, pixel_labels







						def       __magic_name__							(							self					:      List[str]  ):



								'''simple docstring'''



								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       __magic_name__							(							self					:      Optional[Any]			,			snake_case_					:      Optional[int]			,			snake_case_					:      Optional[int]			,			snake_case_					:      Optional[Any]			,			snake_case_					:      Optional[Any]  ):



								'''simple docstring'''



								snake_case__						:       Optional[Any]       						=  MobileViTVaModel(config=snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       Dict       						=  model(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       __magic_name__							(							self					:      Union[str, Any]			,			snake_case_					:      Optional[int]			,			snake_case_					:      List[Any]			,			snake_case_					:      Tuple			,			snake_case_					:      Optional[Any]  ):



								'''simple docstring'''



								snake_case__						:       Optional[int]       						=  self.num_labels
								snake_case__						:       Optional[Any]       						=  MobileViTVaForImageClassification(snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       int       						=  model(snake_case_			,			labels=snake_case_  )
								self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)  )







						def       __magic_name__							(							self					:      int			,			snake_case_					:      List[Any]			,			snake_case_					:      Dict			,			snake_case_					:      Any			,			snake_case_					:      List[str]  ):



								'''simple docstring'''



								snake_case__						:       Dict       						=  self.num_labels
								snake_case__						:       Any       						=  MobileViTVaForSemanticSegmentation(snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       str       						=  model(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__						:       Optional[int]       						=  model(snake_case_			,			labels=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       __magic_name__							(							self					:      str  ):



								'''simple docstring'''



								snake_case__						:       Dict       						=  self.prepare_config_and_inputs()
								snake_case__						,       snake_case__						,       snake_case__						,       snake_case__						:       List[str]       						=  config_and_inputs
								snake_case__						:       List[str]       						=  {'''pixel_values''': pixel_values}
								return config, inputs_dict





@require_torch
class     a			(				SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE			,			unittest.TestCase       ):






						"""simple docstring"""




						__UpperCAmelCase			     =    (
						    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)

						__UpperCAmelCase			     =    (
						    {
						        """feature-extraction""": MobileViTVaModel,
						        """image-classification""": MobileViTVaForImageClassification,
						        """image-segmentation""": MobileViTVaForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						__UpperCAmelCase			     =    False
						__UpperCAmelCase			     =    False
						__UpperCAmelCase			     =    False
						__UpperCAmelCase			     =    False







						def       __magic_name__							(							self					:      int  ):



								'''simple docstring'''



								snake_case__						:       str       						=  MobileViTVaModelTester(self  )
								snake_case__						:       Union[str, Any]       						=  MobileViTVaConfigTester(self			,			config_class=snake_case_			,			has_text_modality=snake_case_  )







						def       __magic_name__							(							self					:      List[str]  ):



								'''simple docstring'''



								self.config_tester.run_common_tests()







						@unittest.skip(reason='''MobileViTV2 does not use inputs_embeds'''  )
						def       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								pass







						@unittest.skip(reason='''MobileViTV2 does not support input and output embeddings'''  )
						def       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								pass







						@unittest.skip(reason='''MobileViTV2 does not output attentions'''  )
						def       __magic_name__							(							self					:      int  ):



								'''simple docstring'''



								pass







						@require_torch_multi_gpu
						@unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.'''  )
						def       __magic_name__							(							self					:      int  ):



								'''simple docstring'''



								pass







						@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''  )
						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



								pass







						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



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

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

										snake_case__						:       Optional[int]       						=  ['''pixel_values''']
										self.assertListEqual(arg_names[:1]			,			snake_case_  )







						def       __magic_name__							(							self					:      List[str]  ):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      List[str]  ):



								'''simple docstring'''



								def check_hidden_states_output(snake_case_					:      Tuple			,			snake_case_					:      Optional[Any]			,			snake_case_					:      Tuple  ):
										snake_case__						:       Optional[Any]       						=  model_class(snake_case_  )
										model.to(snake_case_  )
										model.eval()

										with torch.no_grad():
												snake_case__						:       Tuple       						=  model(**self._prepare_for_class(snake_case_			,			snake_case_  )  )

										snake_case__						:       Union[str, Any]       						=  outputs.hidden_states

										snake_case__						:       Any       						=  5
										self.assertEqual(len(snake_case_  )			,			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__						:       Dict       						=  2
										for i in range(len(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__						:       Union[str, Any]       						=  self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
										snake_case__						:       List[str]       						=  True
										check_hidden_states_output(snake_case_			,			snake_case_			,			snake_case_  )

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

										check_hidden_states_output(snake_case_			,			snake_case_			,			snake_case_  )







						def       __magic_name__							(							self					:      int  ):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      Any  ):



								'''simple docstring'''



								snake_case__						:       Dict       						=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*snake_case_  )







						@slow
						def       __magic_name__							(							self					:      List[Any]  ):



								'''simple docstring'''



								for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										snake_case__						:       Any       						=  MobileViTVaModel.from_pretrained(snake_case_  )
										self.assertIsNotNone(snake_case_  )





def 	_a       (				):

		"""simple docstring"""

		snake_case__						:       Optional[Any]       						=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
		return image





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






						"""simple docstring"""




						@cached_property
						def       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								return (
								    MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''  )
								    if is_vision_available()
								    else None
								)







						@slow
						def       __magic_name__							(							self					:      Tuple  ):



								'''simple docstring'''



								snake_case__						:       Tuple       						=  MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''  ).to(
								    snake_case_  )

								snake_case__						:       Any       						=  self.default_image_processor
								snake_case__						:       Tuple       						=  prepare_img()
								snake_case__						:       str       						=  image_processor(images=snake_case_			,			return_tensors='''pt'''  ).to(snake_case_  )

								# forward pass
								with torch.no_grad():
										snake_case__						:       Any       						=  model(**snake_case_  )

								# verify the logits
								snake_case__						:       Dict       						=  torch.Size((1, 1_0_0_0)  )
								self.assertEqual(outputs.logits.shape			,			snake_case_  )

								snake_case__						:       Tuple       						=  torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01]  ).to(snake_case_  )

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







						@slow
						def       __magic_name__							(							self					:      Tuple  ):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''  )
								snake_case__						:       Any       						=  model.to(snake_case_  )

								snake_case__						:       Tuple       						=  MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''  )

								snake_case__						:       str       						=  prepare_img()
								snake_case__						:       Union[str, Any]       						=  image_processor(images=snake_case_			,			return_tensors='''pt'''  ).to(snake_case_  )

								# forward pass
								with torch.no_grad():
										snake_case__						:       Union[str, Any]       						=  model(**snake_case_  )
								snake_case__						:       Tuple       						=  outputs.logits

								# verify the logits
								snake_case__						:       Optional[Any]       						=  torch.Size((1, 2_1, 3_2, 3_2)  )
								self.assertEqual(logits.shape			,			snake_case_  )

								snake_case__						:       List[Any]       						=  torch.tensor(
								    [
								        [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]],
								        [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]],
								        [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]],
								    ]			,			device=snake_case_			,			)

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







						@slow
						def       __magic_name__							(							self					:      List[Any]  ):



								'''simple docstring'''



								snake_case__						:       Optional[int]       						=  MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''  )
								snake_case__						:       List[str]       						=  model.to(snake_case_  )

								snake_case__						:       Optional[int]       						=  MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''  )

								snake_case__						:       str       						=  prepare_img()
								snake_case__						:       str       						=  image_processor(images=snake_case_			,			return_tensors='''pt'''  ).to(snake_case_  )

								# forward pass
								with torch.no_grad():
										snake_case__						:       Any       						=  model(**snake_case_  )

								snake_case__						:       str       						=  outputs.logits.detach().cpu()

								snake_case__						:       int       						=  image_processor.post_process_semantic_segmentation(outputs=snake_case_			,			target_sizes=[(5_0, 6_0)]  )
								snake_case__						:       int       						=  torch.Size((5_0, 6_0)  )
								self.assertEqual(segmentation[0].shape			,			snake_case_  )

								snake_case__						:       str       						=  image_processor.post_process_semantic_segmentation(outputs=snake_case_  )
								snake_case__						:       Any       						=  torch.Size((3_2, 3_2)  )
								self.assertEqual(segmentation[0].shape			,			snake_case_  )



