



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


						'''simple docstring'''





						def     _snake_case	(	self	:							Optional[Any]	):






							'''simple docstring'''



							__lowercase		       =			self.config_class(**self.inputs_dict	)
							self.parent.assertTrue(hasattr(lowerCamelCase							,      "hidden_sizes"	)	)
							self.parent.assertTrue(hasattr(lowerCamelCase							,      "neck_hidden_sizes"	)	)
							self.parent.assertTrue(hasattr(lowerCamelCase							,      "num_attention_heads"	)	)

class   _A   :


						'''simple docstring'''





						def __init__(	self	:							Union[str, Any]							,      lowerCamelCase	:							Tuple							,      lowerCamelCase	:							str=13							,      lowerCamelCase	:							Union[str, Any]=32							,      lowerCamelCase	:							Any=2							,      lowerCamelCase	:							int=3							,      lowerCamelCase	:							Optional[int]=640							,      lowerCamelCase	:							Optional[Any]=4							,      lowerCamelCase	:							List[str]="silu"							,      lowerCamelCase	:							Any=3							,      lowerCamelCase	:							List[Any]=32							,      lowerCamelCase	:							int=0.1							,      lowerCamelCase	:							Dict=0.1							,      lowerCamelCase	:							Optional[int]=0.1							,      lowerCamelCase	:							List[Any]=0.02							,      lowerCamelCase	:							int=True							,      lowerCamelCase	:							int=True							,      lowerCamelCase	:							int=10							,      lowerCamelCase	:							str=None							,      ):






							'''simple docstring'''



							__lowercase		       =			parent
							__lowercase		       =			batch_size
							__lowercase		       =			image_size
							__lowercase		       =			patch_size
							__lowercase		       =			num_channels
							__lowercase		       =			last_hidden_size
							__lowercase		       =			num_attention_heads
							__lowercase		       =			hidden_act
							__lowercase		       =			conv_kernel_size
							__lowercase		       =			output_stride
							__lowercase		       =			hidden_dropout_prob
							__lowercase		       =			attention_probs_dropout_prob
							__lowercase		       =			classifier_dropout_prob
							__lowercase		       =			use_labels
							__lowercase		       =			is_training
							__lowercase		       =			num_labels
							__lowercase		       =			initializer_range
							__lowercase		       =			scope



						def     _snake_case	(	self	:							Tuple	):






							'''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	:							Optional[Any]	):






							'''simple docstring'''



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






							'''simple docstring'''



							__lowercase		       =			MobileViTModel(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	:							Tuple							,      lowerCamelCase	:							int							,      lowerCamelCase	:							Optional[Any]							,      lowerCamelCase	:							Any							,      lowerCamelCase	:							Dict	):






							'''simple docstring'''



							__lowercase		       =			self.num_labels
							__lowercase		       =			MobileViTForImageClassification(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	:							Dict							,      lowerCamelCase	:							Optional[int]							,      lowerCamelCase	:							int							,      lowerCamelCase	:							Optional[Any]							,      lowerCamelCase	:							Any	):






							'''simple docstring'''



							__lowercase		       =			self.num_labels
							__lowercase		       =			MobileViTForSemanticSegmentation(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	:							Optional[int]	):






							'''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			:     Optional[Any]      							=      (
						    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)
						_snake_case			:     str      							=      (
						    {
						        """feature-extraction""": MobileViTModel,
						        """image-classification""": MobileViTForImageClassification,
						        """image-segmentation""": MobileViTForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						_snake_case			:     Any      							=      False
						_snake_case			:     int      							=      False
						_snake_case			:     Tuple      							=      False
						_snake_case			:     str      							=      False



						def     _snake_case	(	self	:							List[Any]	):






							'''simple docstring'''



							__lowercase		       =			MobileViTModelTester(self	)
							__lowercase		       =			MobileViTConfigTester(self							,      config_class=lowerCamelCase							,      has_text_modality=lowerCamelCase	)



						def     _snake_case	(	self	:							Tuple	):






							'''simple docstring'''



							self.config_tester.run_common_tests()



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






							'''simple docstring'''



							pass



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






							'''simple docstring'''



							pass



						@unittest.skip(reason="MobileViT does not output attentions"	)
						def     _snake_case	(	self	:							Union[str, Any]	):






							'''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	)



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






							'''simple docstring'''



							pass



						def     _snake_case	(	self	:							Optional[int]	):






							'''simple docstring'''



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



						def     _snake_case	(	self	:							str	):






							'''simple docstring'''



							def check_hidden_states_output(lowerCamelCase	:							Optional[int]							,      lowerCamelCase	:							int							,      lowerCamelCase	:							Any	):
								__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	)

								# MobileViT'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	:							Optional[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	:							Union[str, Any]	):






							'''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	:							Optional[int]	):






							'''simple docstring'''



							for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								__lowercase		       =			MobileViTModel.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	:							List[Any]	):






							'''simple docstring'''



							return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small"	) if is_vision_available() else None



						@slow
						def     _snake_case	(	self	:							Any	):






							'''simple docstring'''



							__lowercase		       =			MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"	).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.9364, -1.2327, -0.4653]	).to(lowerCamelCase	)

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



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






							'''simple docstring'''



							__lowercase		       =			MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"	)
							__lowercase		       =			model.to(lowerCamelCase	)

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

							__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(
							    [
							        [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
							        [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
							        [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
							    ]							,      device=lowerCamelCase							,      )

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



						@slow
						def     _snake_case	(	self	:							str	):






							'''simple docstring'''



							__lowercase		       =			MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"	)
							__lowercase		       =			model.to(lowerCamelCase	)

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

							__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	)








from __future__ import annotations

from typing import Any

class   _A   :


						'''simple docstring'''





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






							'''simple docstring'''



							__lowercase		       =			num_of_nodes
							__lowercase		       =			[]
							__lowercase		       =			{}



						def     _snake_case	(	self	:							Dict							,      lowerCamelCase	:							int							,      lowerCamelCase	:							int							,      lowerCamelCase	:							int	):






							'''simple docstring'''



							self.m_edges.append([u_node, v_node, weight]	)



						def     _snake_case	(	self	:							List[Any]							,      lowerCamelCase	:							int	):






							'''simple docstring'''



							if self.m_component[u_node] == u_node:
								return u_node
							return self.find_component(self.m_component[u_node]	)



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






							'''simple docstring'''



							if self.m_component[u_node] != u_node:
								for k in self.m_component:
									__lowercase		       =			self.find_component(lowerCamelCase	)



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






							'''simple docstring'''



							if component_size[u_node] <= component_size[v_node]:
								__lowercase		       =			v_node
								component_size[v_node] += component_size[u_node]
								self.set_component(lowerCamelCase	)

							elif component_size[u_node] >= component_size[v_node]:
								__lowercase		       =			self.find_component(lowerCamelCase	)
								component_size[u_node] += component_size[v_node]
								self.set_component(lowerCamelCase	)



						def     _snake_case	(	self	:							Any	):






							'''simple docstring'''



							__lowercase		       =			[]
							__lowercase		       =			0

							__lowercase		       =			[-1] * self.m_num_of_nodes

							# A list of components (initialized to all of the nodes)
							for node in range(self.m_num_of_nodes	):
								self.m_component.update({node: node}	)
								component_size.append(1	)

							__lowercase		       =			self.m_num_of_nodes

							while num_of_components > 1:
								for edge in self.m_edges:
									__lowercase       ,    __lowercase       ,    __lowercase		       =			edge

									__lowercase		       =			self.m_component[u]
									__lowercase		       =			self.m_component[v]

									if u_component != v_component:

										for component in (u_component, v_component):
											if (
											    minimum_weight_edge[component] == -1
											    or minimum_weight_edge[component][2] > w
											):
												__lowercase		       =			[u, v, w]

								for edge in minimum_weight_edge:
									if isinstance(lowerCamelCase							,      lowerCamelCase	):
										__lowercase       ,    __lowercase       ,    __lowercase		       =			edge

										__lowercase		       =			self.m_component[u]
										__lowercase		       =			self.m_component[v]

										if u_component != v_component:
											mst_weight += w
											self.union(lowerCamelCase							,      lowerCamelCase							,      lowerCamelCase	)
											print(f"""Added edge [{u} - {v}]\nAdded weight: {w}\n"""	)
											num_of_components -= 1

								__lowercase		       =			[-1] * self.m_num_of_nodes
							print(f"""The total weight of the minimal spanning tree is: {mst_weight}"""	)



def    snake_case_				(    ):
	pass


if __name__ == "__main__":
	import doctest

	doctest.testmod()



