




import inspect
import unittest

from transformers import MobileNetVaConfig
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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
	from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import MobileNetVaImageProcessor





class 					snake_case_   (     __A	):



				'''simple docstring'''





				def    __SCREAMING_SNAKE_CASE     (      self							:   Any							)							->			List[str]:
											lowerCamelCase_			:    int   						=      self.config_class(**self.inputs_dict							)
											self.parent.assertTrue(hasattr(__a      ,							"tf_padding"							)							)
											self.parent.assertTrue(hasattr(__a      ,							"depth_multiplier"							)							)





class 					snake_case_   :



				'''simple docstring'''





				def __init__(      self							:   Union[str, Any]      ,							__magic_name__							:   str      ,							__magic_name__							:   Tuple=13      ,							__magic_name__							:   int=3      ,							__magic_name__							:   List[Any]=32      ,							__magic_name__							:   List[Any]=0.25      ,							__magic_name__							:   Optional[int]=8      ,							__magic_name__							:   List[Any]=8      ,							__magic_name__							:   Optional[int]=6      ,							__magic_name__							:   Dict=32      ,							__magic_name__							:   int=True      ,							__magic_name__							:   str=True      ,							__magic_name__							:   Union[str, Any]=True      ,							__magic_name__							:   int="relu6"      ,							__magic_name__							:   Tuple=1280      ,							__magic_name__							:   Tuple=0.1      ,							__magic_name__							:   Dict=0.02      ,							__magic_name__							:   Union[str, Any]=True      ,							__magic_name__							:   Any=True      ,							__magic_name__							:   str=10      ,							__magic_name__							:   Any=None      ,							)							->			Union[str, Any]:
											lowerCamelCase_			:    int   						=      parent
											lowerCamelCase_			:    int   						=      batch_size
											lowerCamelCase_			:    List[str]   						=      num_channels
											lowerCamelCase_			:    List[Any]   						=      image_size
											lowerCamelCase_			:    List[str]   						=      depth_multiplier
											lowerCamelCase_			:    Dict   						=      depth_divisible_by
											lowerCamelCase_			:    Tuple   						=      min_depth
											lowerCamelCase_			:    int   						=      expand_ratio
											lowerCamelCase_			:    Optional[Any]   						=      tf_padding
											lowerCamelCase_			:    int   						=      output_stride
											lowerCamelCase_			:    int   						=      first_layer_is_expansion
											lowerCamelCase_			:    Union[str, Any]   						=      finegrained_output
											lowerCamelCase_			:    Dict   						=      hidden_act
											lowerCamelCase_			:    str   						=      last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier							)
											lowerCamelCase_			:    Dict   						=      classifier_dropout_prob
											lowerCamelCase_			:    List[str]   						=      use_labels
											lowerCamelCase_			:    Any   						=      is_training
											lowerCamelCase_			:    List[str]   						=      num_labels
											lowerCamelCase_			:    Dict   						=      initializer_range
											lowerCamelCase_			:    Union[str, Any]   						=      scope





				def    __SCREAMING_SNAKE_CASE     (      self							:   Dict							)							->			List[str]:
											lowerCamelCase_			:    List[str]   						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

											lowerCamelCase_			:    str   						=      self.get_config()

											return config, pixel_values, labels, pixel_labels





				def    __SCREAMING_SNAKE_CASE     (      self							:   Dict							)							->			Union[str, Any]:
											return MobileNetVaConfig(
											    num_channels=self.num_channels      ,							image_size=self.image_size      ,							depth_multiplier=self.depth_multiplier      ,							depth_divisible_by=self.depth_divisible_by      ,							min_depth=self.min_depth      ,							expand_ratio=self.expand_ratio      ,							output_stride=self.output_stride      ,							first_layer_is_expansion=self.first_layer_is_expansion      ,							finegrained_output=self.finegrained_output      ,							hidden_act=self.hidden_act      ,							tf_padding=self.tf_padding      ,							classifier_dropout_prob=self.classifier_dropout_prob      ,							initializer_range=self.initializer_range      ,							)





				def    __SCREAMING_SNAKE_CASE     (      self							:   Union[str, Any]      ,							__magic_name__							:   List[Any]      ,							__magic_name__							:   Tuple      ,							__magic_name__							:   Optional[int]      ,							__magic_name__							:   Optional[Any]							)							->			int:
											lowerCamelCase_			:    List[str]   						=      MobileNetVaModel(config=__a							)
											model.to(__a							)
											model.eval()
											lowerCamelCase_			:    int   						=      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,
											    )      ,							)
											self.parent.assertEqual(
											    result.pooler_output.shape      ,							(self.batch_size, self.last_hidden_size)      ,							)





				def    __SCREAMING_SNAKE_CASE     (      self							:   Optional[Any]      ,							__magic_name__							:   Dict      ,							__magic_name__							:   int      ,							__magic_name__							:   List[Any]      ,							__magic_name__							:   Any							)							->			Dict:
											lowerCamelCase_			:    Dict   						=      self.num_labels
											lowerCamelCase_			:    str   						=      MobileNetVaForImageClassification(__a							)
											model.to(__a							)
											model.eval()
											lowerCamelCase_			:    List[str]   						=      model(__a      ,							labels=__a							)
											self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.num_labels)							)





				def    __SCREAMING_SNAKE_CASE     (      self							:   Optional[int]      ,							__magic_name__							:   int      ,							__magic_name__							:   Optional[int]      ,							__magic_name__							:   Optional[int]      ,							__magic_name__							:   List[Any]							)							->			List[str]:
											lowerCamelCase_			:    Union[str, Any]   						=      self.num_labels
											lowerCamelCase_			:    int   						=      MobileNetVaForSemanticSegmentation(__a							)
											model.to(__a							)
											model.eval()
											lowerCamelCase_			:    Optional[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,
											    )      ,							)
											lowerCamelCase_			:    int   						=      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    __SCREAMING_SNAKE_CASE     (      self							:   Optional[int]							)							->			Dict:
											lowerCamelCase_			:    int   						=      self.prepare_config_and_inputs()
											lowerCamelCase_						,						lowerCamelCase_						,						lowerCamelCase_						,						lowerCamelCase_			:    Dict   						=      config_and_inputs
											lowerCamelCase_			:    Any   						=      {"pixel_values": pixel_values}
											return config, inputs_dict





@require_torch
class 					snake_case_   (     __A   ,	__A   ,	unittest.TestCase	):



				'''simple docstring'''
				lowerCamelCase       =  (
				    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)
				lowerCamelCase       =  (
				    {
				        "feature-extraction": MobileNetVaModel,
				        "image-classification": MobileNetVaForImageClassification,
				        "image-segmentation": MobileNetVaForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				lowerCamelCase       =  False
				lowerCamelCase       =  False
				lowerCamelCase       =  False
				lowerCamelCase       =  False





				def    __SCREAMING_SNAKE_CASE     (      self							:   Union[str, Any]							)							->			int:
											lowerCamelCase_			:    Optional[int]   						=      MobileNetVaModelTester(self							)
											lowerCamelCase_			:    Dict   						=      MobileNetVaConfigTester(self      ,							config_class=__a      ,							has_text_modality=__a							)





				def    __SCREAMING_SNAKE_CASE     (      self							:   Tuple							)							->			Optional[Any]:
											self.config_tester.run_common_tests()





				@unittest.skip(reason="MobileNetV2 does not use inputs_embeds"							)
				def    __SCREAMING_SNAKE_CASE     (      self							:   Dict							)							->			str:
											pass





				@unittest.skip(reason="MobileNetV2 does not support input and output embeddings"							)
				def    __SCREAMING_SNAKE_CASE     (      self							:   Union[str, Any]							)							->			Optional[int]:
											pass





				@unittest.skip(reason="MobileNetV2 does not output attentions"							)
				def    __SCREAMING_SNAKE_CASE     (      self							:   Dict							)							->			Optional[int]:
											pass





				def    __SCREAMING_SNAKE_CASE     (      self							:   Optional[Any]							)							->			int:
											lowerCamelCase_						,						lowerCamelCase_			:    Any   						=      self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		lowerCamelCase_			:    Dict   						=      model_class(__a							)
																		lowerCamelCase_			:    List[str]   						=      inspect.signature(model.forward							)
																		# signature.parameters is an OrderedDict => so arg_names order is deterministic
																		lowerCamelCase_			:    Tuple   						=      [*signature.parameters.keys()]

																		lowerCamelCase_			:    Dict   						=      ["pixel_values"]
																		self.assertListEqual(arg_names[:1]      ,							__a							)





				def    __SCREAMING_SNAKE_CASE     (      self							:   Tuple							)							->			Any:
											lowerCamelCase_			:    Union[str, Any]   						=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__a							)





				def    __SCREAMING_SNAKE_CASE     (      self							:   Optional[int]							)							->			Tuple:
											def check_hidden_states_output(__magic_name__							:   Optional[Any]      ,							__magic_name__							:   Tuple      ,							__magic_name__							:   List[Any]							):
																		lowerCamelCase_			:    str   						=      model_class(__a							)
																		model.to(__a							)
																		model.eval()

																		with torch.no_grad():
																									lowerCamelCase_			:    Optional[Any]   						=      model(**self._prepare_for_class(__a      ,							__a							)							)

																		lowerCamelCase_			:    List[str]   						=      outputs.hidden_states

																		lowerCamelCase_			:    List[str]   						=      16
																		self.assertEqual(len(__a							)      ,							__a							)

											lowerCamelCase_						,						lowerCamelCase_			:    List[Any]   						=      self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		lowerCamelCase_			:    Dict   						=      True
																		check_hidden_states_output(__a      ,							__a      ,							__a							)

																		# check that output_hidden_states also work using config
																		del inputs_dict["output_hidden_states"]
																		lowerCamelCase_			:    Union[str, Any]   						=      True

																		check_hidden_states_output(__a      ,							__a      ,							__a							)





				def    __SCREAMING_SNAKE_CASE     (      self							:   Optional[Any]							)							->			int:
											lowerCamelCase_			:    Dict   						=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__a							)





				def    __SCREAMING_SNAKE_CASE     (      self							:   Tuple							)							->			Optional[int]:
											lowerCamelCase_			:    List[Any]   						=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*__a							)





				@slow
				def    __SCREAMING_SNAKE_CASE     (      self							:   List[str]							)							->			Tuple:
											for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		lowerCamelCase_			:    int   						=      MobileNetVaModel.from_pretrained(__a							)
																		self.assertIsNotNone(__a							)



def        __a							(  ) ->					str:
							"""simple docstring"""




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





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



				'''simple docstring'''





				@cached_property
				def    __SCREAMING_SNAKE_CASE     (      self							:   Optional[int]							)							->			Union[str, Any]:
											return (
											    MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224"							) if is_vision_available() else None
											)





				@slow
				def    __SCREAMING_SNAKE_CASE     (      self							:   List[str]							)							->			Dict:
											lowerCamelCase_			:    Optional[int]   						=      MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"							).to(__a							)

											lowerCamelCase_			:    Tuple   						=      self.default_image_processor
											lowerCamelCase_			:    List[Any]   						=      prepare_img()
											lowerCamelCase_			:    List[str]   						=      image_processor(images=__a      ,							return_tensors="pt"							).to(__a							)

											# forward pass
											with torch.no_grad():
																		lowerCamelCase_			:    int   						=      model(**__a							)

											# verify the logits
											lowerCamelCase_			:    List[Any]   						=      torch.Size((1, 1001)							)
											self.assertEqual(outputs.logits.shape      ,							__a							)

											lowerCamelCase_			:    Union[str, Any]   						=      torch.tensor([0.2445, -1.1993, 0.1905]							).to(__a							)

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





				@slow
				def    __SCREAMING_SNAKE_CASE     (      self							:   List[str]							)							->			List[str]:
											lowerCamelCase_			:    Tuple   						=      MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"							)
											lowerCamelCase_			:    int   						=      model.to(__a							)

											lowerCamelCase_			:    List[str]   						=      MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"							)

											lowerCamelCase_			:    Optional[Any]   						=      prepare_img()
											lowerCamelCase_			:    Optional[int]   						=      image_processor(images=__a      ,							return_tensors="pt"							).to(__a							)

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

											# verify the logits
											lowerCamelCase_			:    Union[str, Any]   						=      torch.Size((1, 21, 65, 65)							)
											self.assertEqual(logits.shape      ,							__a							)

											lowerCamelCase_			:    int   						=      torch.tensor(
											    [
											        [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
											        [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
											        [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
											    ]      ,							device=__a      ,							)

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


'''simple docstring'''


from random import randint, random





def    lowerCAmelCase       (		UpperCamelCase__					: int     ,       UpperCamelCase__					: int     ,       UpperCamelCase__					: int     ,       UpperCamelCase__					: bool = False     ,       UpperCamelCase__					: bool = False     ,       UpperCamelCase__					: int = 5     ,       ):


	"""simple docstring"""
	__UpperCAmelCase      					=      [[-1] * number_of_cells]  # Create a highway without any car
	__UpperCAmelCase      					=      0
	__UpperCAmelCase      					=      max(UpperCamelCase__     ,       0							)
	while i < number_of_cells:
		__UpperCAmelCase      					=      (
		    randint(0     ,       UpperCamelCase__							) if random_speed else initial_speed
		)  # Place the cars
		i += (
		    randint(1     ,       max_speed * 2							) if random_frequency else frequency
		)  # Arbitrary number, may need tuning
	return highway





def    lowerCAmelCase       (		UpperCamelCase__					: list     ,       UpperCamelCase__					: int							):


	"""simple docstring"""
	__UpperCAmelCase      					=      0
	__UpperCAmelCase      					=      highway_now[car_index + 1 :]
	for cell in range(len(UpperCamelCase__							)							):  # May need a better name for this
		if cells[cell] != -1:  # If the cell is not empty then
			return distance  # we have the distance we wanted
		distance += 1
	# Here if the car is near the end of the highway
	return distance + get_distance(UpperCamelCase__     ,       -1							)





def    lowerCAmelCase       (		UpperCamelCase__					: list     ,       UpperCamelCase__					: float     ,       UpperCamelCase__					: int							):


	"""simple docstring"""
	__UpperCAmelCase      					=      len(UpperCamelCase__							)
	# Beforce calculations, the highway is empty
	__UpperCAmelCase      					=      [-1] * number_of_cells

	for car_index in range(UpperCamelCase__							):
		if highway_now[car_index] != -1:
			# Add 1 to the current speed of the car and cap the speed
			__UpperCAmelCase      					=      min(highway_now[car_index] + 1     ,       UpperCamelCase__							)
			# Number of empty cell before the next car
			__UpperCAmelCase      					=      get_distance(UpperCamelCase__     ,       UpperCamelCase__							) - 1
			# We can't have the car causing an accident
			__UpperCAmelCase      					=      min(next_highway[car_index]     ,       UpperCamelCase__							)
			if random() < probability:
				# Randomly, a driver will slow down
				__UpperCAmelCase      					=      max(next_highway[car_index] - 1     ,       0							)
	return next_highway





def    lowerCAmelCase       (		UpperCamelCase__					: list     ,       UpperCamelCase__					: int     ,       UpperCamelCase__					: float     ,       UpperCamelCase__					: int							):


	"""simple docstring"""
	__UpperCAmelCase      					=      len(highway[0]							)

	for i in range(UpperCamelCase__							):
		__UpperCAmelCase      					=      update(highway[i]     ,       UpperCamelCase__     ,       UpperCamelCase__							)
		__UpperCAmelCase      					=      [-1] * number_of_cells

		for car_index in range(UpperCamelCase__							):
			__UpperCAmelCase      					=      next_speeds_calculated[car_index]
			if speed != -1:
				# Change the position based on the speed (with % to create the loop)
				__UpperCAmelCase      					=      (car_index + speed) % number_of_cells
				# Commit the change of position
				__UpperCAmelCase      					=      speed
		highway.append(UpperCamelCase__							)

	return highway


if __name__ == "__main__":
					import doctest

					doctest.testmod()
