





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 							lowerCAmelCase__  (	__a						):







					def  _lowercase			(       self      :     Optional[int]):
											A__	:							Optional[Any]						    = self.config_class(**self.inputs_dict)
											self.parent.assertTrue(hasattr(a_			,		"hidden_sizes"))
											self.parent.assertTrue(hasattr(a_			,		"neck_hidden_sizes"))
											self.parent.assertTrue(hasattr(a_			,		"num_attention_heads"))




class 							lowerCAmelCase__  :







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







					def  _lowercase			(       self      :     Tuple):
											A__	:							Tuple						    = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

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

											return config, pixel_values, labels, pixel_labels







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







					def  _lowercase			(       self      :     str			,		_A      :     Any			,		_A      :     Union[str, Any]			,		_A      :     Tuple			,		_A      :     int):
											A__	:							Optional[Any]						    = self.num_labels
											A__	:							Tuple						    = MobileViTForSemanticSegmentation(a_)
											model.to(a_)
											model.eval()
											A__	:							int						    = 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,
											    )			,		)
											A__	:							Tuple						    = 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  _lowercase			(       self      :     List[str]):
											A__	:							Any						    = self.prepare_config_and_inputs()
											A__	:							Any						    = config_and_inputs
											A__	:							Any						    = {"""pixel_values""": pixel_values}
											return config, inputs_dict




@require_torch
class 							lowerCAmelCase__  (	__a					,							__a					,							unittest.TestCase						):
					__A     :    List[str]           =						(
					    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
					    if is_torch_available()
					    else ()
					)
					__A     :    Optional[Any]           =						(
					    {
					        'feature-extraction': MobileViTModel,
					        'image-classification': MobileViTForImageClassification,
					        'image-segmentation': MobileViTForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					__A     :    Union[str, Any]           =						False
					__A     :    Dict           =						False
					__A     :    str           =						False
					__A     :    Optional[Any]           =						False







					def  _lowercase			(       self      :     Optional[Any]):
											A__	:							Optional[int]						    = MobileViTModelTester(self)
											A__	:							Dict						    = MobileViTConfigTester(self			,		config_class=a_			,		has_text_modality=a_)







					def  _lowercase			(       self      :     Optional[int]):
											self.config_tester.run_common_tests()







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







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







					@unittest.skip(reason="MobileViT does not output attentions")
					def  _lowercase			(       self      :     Optional[int]):
											pass







					def  _lowercase			(       self      :     Tuple):
											A__	:							Union[str, Any]						    = self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	A__	:							Any						    = model_class(a_)
																	A__	:							Union[str, Any]						    = inspect.signature(model.forward)
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	A__	:							List[Any]						    = [*signature.parameters.keys()]

																	A__	:							List[Any]						    = ["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]			,		a_)







					@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
					def  _lowercase			(       self      :     Union[str, Any]):
											pass







					def  _lowercase			(       self      :     Optional[int]):
											A__	:							int						    = self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*a_)







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



											def check_hidden_states_output(_A      :     Union[str, Any]			,		_A      :     int			,		_A      :     int):
																	A__	:							Union[str, Any]						    = model_class(a_)
																	model.to(a_)
																	model.eval()

																	with torch.no_grad():
																							A__	:							Union[str, Any]						    = model(**self._prepare_for_class(a_			,		a_))

																	A__	:							List[Any]						    = outputs.hidden_states

																	A__	:							Any						    = 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.
																	A__	:							Union[str, Any]						    = 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)

											A__	:							Dict						    = self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	A__	:							List[Any]						    = True
																	check_hidden_states_output(a_			,		a_			,		a_)

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

																	check_hidden_states_output(a_			,		a_			,		a_)







					def  _lowercase			(       self      :     Tuple):
											A__	:							Optional[int]						    = self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*a_)







					def  _lowercase			(       self      :     int):
											A__	:							Dict						    = self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*a_)







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



											for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	A__	:							List[str]						    = MobileViTModel.from_pretrained(a_)
																	self.assertIsNotNone(a_)




def 	snake_case__       (					)		->		int:







						"""simple docstring"""

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




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







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







					@slow
					def  _lowercase			(       self      :     Optional[int]):
											A__	:							Optional[int]						    = MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small").to(a_)

											A__	:							Union[str, Any]						    = self.default_image_processor
											A__	:							Optional[int]						    = prepare_img()
											A__	:							List[Any]						    = image_processor(images=a_			,		return_tensors="pt").to(a_)

											# forward pass
											with torch.no_grad():
																	A__	:							Union[str, Any]						    = model(**a_)

											# verify the logits
											A__	:							List[str]						    = torch.Size((1, 1000))
											self.assertEqual(outputs.logits.shape			,		a_)

											A__	:							str						    = torch.tensor([-1.93_64, -1.23_27, -0.46_53]).to(a_)

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







					@slow
					def  _lowercase			(       self      :     Optional[Any]):
											A__	:							Optional[int]						    = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")
											A__	:							Union[str, Any]						    = model.to(a_)

											A__	:							int						    = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

											A__	:							List[Any]						    = prepare_img()
											A__	:							str						    = image_processor(images=a_			,		return_tensors="pt").to(a_)

											# forward pass
											with torch.no_grad():
																	A__	:							Dict						    = model(**a_)
											A__	:							Union[str, Any]						    = outputs.logits

											# verify the logits
											A__	:							List[Any]						    = torch.Size((1, 21, 32, 32))
											self.assertEqual(logits.shape			,		a_)

											A__	:							Optional[Any]						    = torch.tensor(
											    [
											        [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
											        [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
											        [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
											    ]			,		device=a_			,		)

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







					@slow
					def  _lowercase			(       self      :     str):
											A__	:							List[Any]						    = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")
											A__	:							Dict						    = model.to(a_)

											A__	:							str						    = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

											A__	:							Any						    = prepare_img()
											A__	:							Tuple						    = image_processor(images=a_			,		return_tensors="pt").to(a_)

											# forward pass
											with torch.no_grad():
																	A__	:							Tuple						    = model(**a_)

											A__	:							Union[str, Any]						    = outputs.logits.detach().cpu()

											A__	:							Optional[int]						    = image_processor.post_process_semantic_segmentation(outputs=a_			,		target_sizes=[(50, 60)])
											A__	:							str						    = torch.Size((50, 60))
											self.assertEqual(segmentation[0].shape			,		a_)

											A__	:							Optional[int]						    = image_processor.post_process_semantic_segmentation(outputs=a_)
											A__	:							Optional[Any]						    = torch.Size((32, 32))
											self.assertEqual(segmentation[0].shape			,		a_)




from collections import Counter
from timeit import timeit
def 	snake_case__       (					__lowercase = ""							,     )		->		bool:







						"""simple docstring"""

						return sum(c % 2 for c in Counter(input_str.replace(" "							,     ""       ).lower()       ).values()       ) < 2
def 	snake_case__       (					__lowercase = ""       )		->		bool:







						"""simple docstring"""

						if len(__lowercase       ) == 0:
												return True
						A__	:							Any						    = input_str.replace(" "							,     ""       ).lower()
						# character_freq_dict: Stores the frequency of every character in the input string
						A__	:							dict[str, int]						    = {}

						for character in lower_case_input_str:
												A__	:							Optional[int]						    = character_freq_dict.get(__lowercase							,     0       ) + 1
						A__	:							List[Any]						    = 0

						for character_count in character_freq_dict.values():
												if character_count % 2:
																		odd_char += 1
						if odd_char > 1:
												return False
						return True
def 	snake_case__       (					__lowercase = ""       )		->		None:







						"""simple docstring"""

						print("\nFor string = "							,     __lowercase							,     ":"       )
						print(
						    "> can_string_be_rearranged_as_palindrome_counter()"							,     "\tans ="							,     can_string_be_rearranged_as_palindrome_counter(__lowercase       )							,     "\ttime ="							,     timeit(
						        "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)"							,     setup="import __main__ as z"							,     )							,     "seconds"							,     )
						print(
						    "> can_string_be_rearranged_as_palindrome()"							,     "\tans ="							,     can_string_be_rearranged_as_palindrome(__lowercase       )							,     "\ttime ="							,     timeit(
						        "z.can_string_be_rearranged_as_palindrome(z.check_str)"							,     setup="import __main__ as z"							,     )							,     "seconds"							,     )


if __name__ == "__main__":
		snake_case    :						Dict  =						input(
		    'Enter string to determine if it can be rearranged as a palindrome or not: '
		).strip()
		benchmark(check_str)
		snake_case    :						Dict  =						can_string_be_rearranged_as_palindrome_counter(check_str)
		print(f"""{check_str} can {'' if status else 'not '}be rearranged as a palindrome""")