



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   ( _lowercase	):


						'''simple docstring'''





						def     _snake_case	(	self	:							Any	):






							'''simple docstring'''



							__lowercase		       =			self.config_class(**self.inputs_dict	)
							self.parent.assertTrue(hasattr(lowerCamelCase							,      "width_multiplier"	)	)

class   _A   :


						'''simple docstring'''





						def __init__(	self	:							int							,      lowerCamelCase	:							str							,      lowerCamelCase	:							List[str]=13							,      lowerCamelCase	:							Optional[int]=64							,      lowerCamelCase	:							List[str]=2							,      lowerCamelCase	:							int=3							,      lowerCamelCase	:							List[str]="swish"							,      lowerCamelCase	:							Dict=3							,      lowerCamelCase	:							Any=32							,      lowerCamelCase	:							Any=0.1							,      lowerCamelCase	:							Optional[int]=0.02							,      lowerCamelCase	:							Any=True							,      lowerCamelCase	:							Union[str, Any]=True							,      lowerCamelCase	:							List[str]=10							,      lowerCamelCase	:							List[Any]=None							,      lowerCamelCase	:							Optional[int]=0.25							,      lowerCamelCase	:							Dict=0.0							,      lowerCamelCase	:							str=0.0							,      ):






							'''simple docstring'''



							__lowercase		       =			parent
							__lowercase		       =			batch_size
							__lowercase		       =			image_size
							__lowercase		       =			patch_size
							__lowercase		       =			num_channels
							__lowercase		       =			make_divisible(512 * width_multiplier							,      divisor=8	)
							__lowercase		       =			hidden_act
							__lowercase		       =			conv_kernel_size
							__lowercase		       =			output_stride
							__lowercase		       =			classifier_dropout_prob
							__lowercase		       =			use_labels
							__lowercase		       =			is_training
							__lowercase		       =			num_labels
							__lowercase		       =			initializer_range
							__lowercase		       =			scope
							__lowercase		       =			width_multiplier
							__lowercase		       =			ffn_dropout
							__lowercase		       =			attn_dropout



						def     _snake_case	(	self	:							Union[str, Any]	):






							'''simple docstring'''



							__lowercase		       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

							__lowercase		       =			self.get_config()

							return config, pixel_values, labels, pixel_labels



						def     _snake_case	(	self	:							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     _snake_case	(	self	:							Dict							,      lowerCamelCase	:							Tuple							,      lowerCamelCase	:							Optional[int]							,      lowerCamelCase	:							List[str]							,      lowerCamelCase	:							Any	):






							'''simple docstring'''



							__lowercase		       =			MobileViTVaModel(config=lowerCamelCase	)
							model.to(lowerCamelCase	)
							model.eval()
							__lowercase		       =			model(lowerCamelCase	)
							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	:							int							,      lowerCamelCase	:							Optional[Any]							,      lowerCamelCase	:							int							,      lowerCamelCase	:							int							,      lowerCamelCase	:							str	):






							'''simple docstring'''



							__lowercase		       =			self.num_labels
							__lowercase		       =			MobileViTVaForImageClassification(lowerCamelCase	)
							model.to(lowerCamelCase	)
							model.eval()
							__lowercase		       =			model(lowerCamelCase							,      labels=lowerCamelCase	)
							self.parent.assertEqual(result.logits.shape							,      (self.batch_size, self.num_labels)	)



						def     _snake_case	(	self	:							Optional[int]							,      lowerCamelCase	:							Union[str, Any]							,      lowerCamelCase	:							Any							,      lowerCamelCase	:							Optional[Any]							,      lowerCamelCase	:							Union[str, Any]	):






							'''simple docstring'''



							__lowercase		       =			self.num_labels
							__lowercase		       =			MobileViTVaForSemanticSegmentation(lowerCamelCase	)
							model.to(lowerCamelCase	)
							model.eval()
							__lowercase		       =			model(lowerCamelCase	)
							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		       =			model(lowerCamelCase							,      labels=lowerCamelCase	)
							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	:							Union[str, Any]	):






							'''simple docstring'''



							__lowercase		       =			self.prepare_config_and_inputs()
							__lowercase       ,    __lowercase       ,    __lowercase       ,    __lowercase		       =			config_and_inputs
							__lowercase		       =			{"pixel_values": pixel_values}
							return config, inputs_dict

@require_torch
class   _A   ( _lowercase  ,						_lowercase  ,						unittest.TestCase	):


						'''simple docstring'''





						_snake_case			:     List[str]      							=      (
						    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)

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

						_snake_case			:     Any      							=      False
						_snake_case			:     int      							=      False
						_snake_case			:     Optional[Any]      							=      False
						_snake_case			:     Any      							=      False



						def     _snake_case	(	self	:							int	):






							'''simple docstring'''



							__lowercase		       =			MobileViTVaModelTester(self	)
							__lowercase		       =			MobileViTVaConfigTester(self							,      config_class=lowerCamelCase							,      has_text_modality=lowerCamelCase	)



						def     _snake_case	(	self	:							Dict	):






							'''simple docstring'''



							self.config_tester.run_common_tests()



						@unittest.skip(reason="MobileViTV2 does not use inputs_embeds"	)
						def     _snake_case	(	self	:							Dict	):






							'''simple docstring'''



							pass



						@unittest.skip(reason="MobileViTV2 does not support input and output embeddings"	)
						def     _snake_case	(	self	:							Dict	):






							'''simple docstring'''



							pass



						@unittest.skip(reason="MobileViTV2 does not output attentions"	)
						def     _snake_case	(	self	:							str	):






							'''simple docstring'''



							pass



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






							'''simple docstring'''



							pass



						@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."	)
						def     _snake_case	(	self	:							int	):






							'''simple docstring'''



							pass



						def     _snake_case	(	self	:							List[Any]	):






							'''simple docstring'''



							__lowercase       ,    __lowercase		       =			self.model_tester.prepare_config_and_inputs_for_common()

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

								__lowercase		       =			["pixel_values"]
								self.assertListEqual(arg_names[:1]							,      lowerCamelCase	)



						def     _snake_case	(	self	:							int	):






							'''simple docstring'''



							__lowercase		       =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase	)



						def     _snake_case	(	self	:							int	):






							'''simple docstring'''



							def check_hidden_states_output(lowerCamelCase	:							Optional[Any]							,      lowerCamelCase	:							List[str]							,      lowerCamelCase	:							Dict	):
								__lowercase		       =			model_class(lowerCamelCase	)
								model.to(lowerCamelCase	)
								model.eval()

								with torch.no_grad():
									__lowercase		       =			model(**self._prepare_for_class(lowerCamelCase							,      lowerCamelCase	)	)

								__lowercase		       =			outputs.hidden_states

								__lowercase		       =			5
								self.assertEqual(len(lowerCamelCase	)							,      lowerCamelCase	)

								# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
								# with the width and height being successively divided by 2.
								__lowercase		       =			2
								for i in range(len(lowerCamelCase	)	):
									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       ,    __lowercase		       =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								__lowercase		       =			True
								check_hidden_states_output(lowerCamelCase							,      lowerCamelCase							,      lowerCamelCase	)

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

								check_hidden_states_output(lowerCamelCase							,      lowerCamelCase							,      lowerCamelCase	)



						def     _snake_case	(	self	:							Union[str, Any]	):






							'''simple docstring'''



							__lowercase		       =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCamelCase	)



						def     _snake_case	(	self	:							List[str]	):






							'''simple docstring'''



							__lowercase		       =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase	)



						@slow
						def     _snake_case	(	self	:							Any	):






							'''simple docstring'''



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



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

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


						'''simple docstring'''





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






							'''simple docstring'''



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



						@slow
						def     _snake_case	(	self	:							Tuple	):






							'''simple docstring'''



							__lowercase		       =			MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"	).to(
							    lowerCamelCase	)

							__lowercase		       =			self.default_image_processor
							__lowercase		       =			prepare_img()
							__lowercase		       =			image_processor(images=lowerCamelCase							,      return_tensors="pt"	).to(lowerCamelCase	)

							# forward pass
							with torch.no_grad():
								__lowercase		       =			model(**lowerCamelCase	)

							# verify the logits
							__lowercase		       =			torch.Size((1, 1_000)	)
							self.assertEqual(outputs.logits.shape							,      lowerCamelCase	)

							__lowercase		       =			torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]	).to(lowerCamelCase	)

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



						@slow
						def     _snake_case	(	self	:							List[str]	):






							'''simple docstring'''



							__lowercase		       =			MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"	)
							__lowercase		       =			model.to(lowerCamelCase	)

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

							__lowercase		       =			prepare_img()
							__lowercase		       =			image_processor(images=lowerCamelCase							,      return_tensors="pt"	).to(lowerCamelCase	)

							# forward pass
							with torch.no_grad():
								__lowercase		       =			model(**lowerCamelCase	)
							__lowercase		       =			outputs.logits

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

							__lowercase		       =			torch.tensor(
							    [
							        [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
							        [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
							        [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
							    ]							,      device=lowerCamelCase							,      )

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



						@slow
						def     _snake_case	(	self	:							Union[str, Any]	):






							'''simple docstring'''



							__lowercase		       =			MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"	)
							__lowercase		       =			model.to(lowerCamelCase	)

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

							__lowercase		       =			prepare_img()
							__lowercase		       =			image_processor(images=lowerCamelCase							,      return_tensors="pt"	).to(lowerCamelCase	)

							# forward pass
							with torch.no_grad():
								__lowercase		       =			model(**lowerCamelCase	)

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

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

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








# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


snake_case__					:     List[str]    		=   {
    """configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""],
    """processing_mgp_str""": ["""MgpstrProcessor"""],
    """tokenization_mgp_str""": ["""MgpstrTokenizer"""],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	snake_case__					:     Dict    		=   [
	    """MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """MgpstrModel""",
	    """MgpstrPreTrainedModel""",
	    """MgpstrForSceneTextRecognition""",
	]

if TYPE_CHECKING:
	from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
	from .processing_mgp_str import MgpstrProcessor
	from .tokenization_mgp_str import MgpstrTokenizer

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_mgp_str import (
		    MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
		    MgpstrForSceneTextRecognition,
		    MgpstrModel,
		    MgpstrPreTrainedModel,
		)
else:
	import sys

	snake_case__					:     Union[str, Any]    		=   _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



