


import inspect
import unittest

from transformers import YolosConfig
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
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch
	from torch import nn

	from transformers import YolosForObjectDetection, YolosModel
	from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor
class 	lowerCamelCase_       :



					'''simple docstring'''







					def __init__(				self ,       snake_case_ ,       snake_case_=1_3 ,       snake_case_=[3_0, 3_0] ,       snake_case_=2 ,       snake_case_=3 ,       snake_case_=True ,       snake_case_=True ,       snake_case_=3_2 ,       snake_case_=5 ,       snake_case_=4 ,       snake_case_=3_7 ,       snake_case_="gelu" ,       snake_case_=0.1 ,       snake_case_=0.1 ,       snake_case_=1_0 ,       snake_case_=0.0_2 ,       snake_case_=3 ,       snake_case_=None ,       snake_case_=8 ,       snake_case_=1_0 ,       )   ->			Optional[int]:







								'''simple docstring'''

								__lowercase 					=   parent
								__lowercase 					=   batch_size
								__lowercase 					=   image_size
								__lowercase 					=   patch_size
								__lowercase 					=   num_channels
								__lowercase 					=   is_training
								__lowercase 					=   use_labels
								__lowercase 					=   hidden_size
								__lowercase 					=   num_hidden_layers
								__lowercase 					=   num_attention_heads
								__lowercase 					=   intermediate_size
								__lowercase 					=   hidden_act
								__lowercase 					=   hidden_dropout_prob
								__lowercase 					=   attention_probs_dropout_prob
								__lowercase 					=   type_sequence_label_size
								__lowercase 					=   initializer_range
								__lowercase 					=   num_labels
								__lowercase 					=   scope
								__lowercase 					=   n_targets
								__lowercase 					=   num_detection_tokens
								# we set the expected sequence length (which is used in several tests)
								# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
								__lowercase 					=   (image_size[1] // patch_size) * (image_size[0] // patch_size)
								__lowercase 					=   num_patches + 1 + self.num_detection_tokens






					def A      (				self						)   ->			Dict:







								'''simple docstring'''

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

								__lowercase 					=   None
								if self.use_labels:
											# labels is a list of Dict (each Dict being the labels for a given example in the batch)
											__lowercase 					=   []
											for i in range(self.batch_size						):
														__lowercase 					=   {}
														__lowercase 					=   torch.randint(
														    high=self.num_labels ,       size=(self.n_targets,) ,       device=snake_case_						)
														__lowercase 					=   torch.rand(self.n_targets ,       4 ,       device=snake_case_						)
														labels.append(snake_case_						)

								__lowercase 					=   self.get_config()

								return config, pixel_values, labels






					def A      (				self						)   ->			Optional[int]:







								'''simple docstring'''

								return YolosConfig(
								    image_size=self.image_size ,       patch_size=self.patch_size ,       num_channels=self.num_channels ,       hidden_size=self.hidden_size ,       num_hidden_layers=self.num_hidden_layers ,       num_attention_heads=self.num_attention_heads ,       intermediate_size=self.intermediate_size ,       hidden_act=self.hidden_act ,       hidden_dropout_prob=self.hidden_dropout_prob ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob ,       is_decoder=snake_case_ ,       initializer_range=self.initializer_range ,       num_detection_tokens=self.num_detection_tokens ,       num_labels=self.num_labels ,       )






					def A      (				self ,       snake_case_ ,       snake_case_ ,       snake_case_						)   ->			Dict:







								'''simple docstring'''

								__lowercase 					=   YolosModel(config=snake_case_						)
								model.to(snake_case_						)
								model.eval()
								__lowercase 					=   model(snake_case_						)
								self.parent.assertEqual(
								    result.last_hidden_state.shape ,       (self.batch_size, self.expected_seq_len, self.hidden_size)						)






					def A      (				self ,       snake_case_ ,       snake_case_ ,       snake_case_						)   ->			List[Any]:







								'''simple docstring'''

								__lowercase 					=   YolosForObjectDetection(snake_case_						)
								model.to(snake_case_						)
								model.eval()

								__lowercase 					=   model(pixel_values=snake_case_						)
								__lowercase 					=   model(snake_case_						)

								self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_detection_tokens, self.num_labels + 1)						)
								self.parent.assertEqual(result.pred_boxes.shape ,       (self.batch_size, self.num_detection_tokens, 4)						)

								__lowercase 					=   model(pixel_values=snake_case_ ,       labels=snake_case_						)

								self.parent.assertEqual(result.loss.shape ,       ()						)
								self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_detection_tokens, self.num_labels + 1)						)
								self.parent.assertEqual(result.pred_boxes.shape ,       (self.batch_size, self.num_detection_tokens, 4)						)






					def A      (				self						)   ->			List[Any]:







								'''simple docstring'''

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




@require_torch
class 	lowerCamelCase_       (				lowerCAmelCase__     ,     lowerCAmelCase__     ,     unittest.TestCase				):



					'''simple docstring'''







					__UpperCAmelCase            =				(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
					__UpperCAmelCase            =				(
					    {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
					)

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






					def A      (				self ,       snake_case_ ,       snake_case_ ,       snake_case_=False						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   super()._prepare_for_class(snake_case_ ,       snake_case_ ,       return_labels=snake_case_						)

								if return_labels:
											if model_class.__name__ == "YolosForObjectDetection":
														__lowercase 					=   []
														for i in range(self.model_tester.batch_size						):
																	__lowercase 					=   {}
																	__lowercase 					=   torch.ones(
																	    size=(self.model_tester.n_targets,) ,       device=snake_case_ ,       dtype=torch.long						)
																	__lowercase 					=   torch.ones(
																	    self.model_tester.n_targets ,       4 ,       device=snake_case_ ,       dtype=torch.float						)
																	labels.append(snake_case_						)
														__lowercase 					=   labels

								return inputs_dict






					def A      (				self						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   YolosModelTester(self						)
								__lowercase 					=   ConfigTester(self ,       config_class=snake_case_ ,       has_text_modality=snake_case_ ,       hidden_size=3_7						)






					def A      (				self						)   ->			str:







								'''simple docstring'''

								self.config_tester.run_common_tests()






					def A      (				self						)   ->			Any:







								'''simple docstring'''

								pass






					def A      (				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(snake_case_						)
											self.assertIsInstance(model.get_input_embeddings() ,       (nn.Module)						)
											__lowercase 					=   model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(snake_case_ ,       nn.Linear						)						)






					def A      (				self						)   ->			Tuple:







								'''simple docstring'''

								__lowercase					, __lowercase 					=   self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											__lowercase 					=   model_class(snake_case_						)
											__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] ,       snake_case_						)






					def A      (				self						)   ->			Union[str, Any]:







								'''simple docstring'''

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






					def A      (				self						)   ->			List[Any]:







								'''simple docstring'''

								__lowercase					, __lowercase 					=   self.model_tester.prepare_config_and_inputs_for_common()
								__lowercase 					=   True

								# in YOLOS, the seq_len is different
								__lowercase 					=   self.model_tester.expected_seq_len
								for model_class in self.all_model_classes:
											__lowercase 					=   True
											__lowercase 					=   False
											__lowercase 					=   True
											__lowercase 					=   model_class(snake_case_						)
											model.to(snake_case_						)
											model.eval()
											with torch.no_grad():
														__lowercase 					=   model(**self._prepare_for_class(snake_case_ ,       snake_case_						)						)
											__lowercase 					=   outputs.attentions
											self.assertEqual(len(snake_case_						) ,       self.model_tester.num_hidden_layers						)

											# check that output_attentions also work using config
											del inputs_dict["output_attentions"]
											__lowercase 					=   True
											__lowercase 					=   model_class(snake_case_						)
											model.to(snake_case_						)
											model.eval()
											with torch.no_grad():
														__lowercase 					=   model(**self._prepare_for_class(snake_case_ ,       snake_case_						)						)
											__lowercase 					=   outputs.attentions
											self.assertEqual(len(snake_case_						) ,       self.model_tester.num_hidden_layers						)

											self.assertListEqual(
											    list(attentions[0].shape[-3:]						) ,       [self.model_tester.num_attention_heads, seq_len, seq_len] ,       )
											__lowercase 					=   len(snake_case_						)

											# Check attention is always last and order is fine
											__lowercase 					=   True
											__lowercase 					=   True
											__lowercase 					=   model_class(snake_case_						)
											model.to(snake_case_						)
											model.eval()
											with torch.no_grad():
														__lowercase 					=   model(**self._prepare_for_class(snake_case_ ,       snake_case_						)						)

											__lowercase 					=   1
											self.assertEqual(out_len + added_hidden_states ,       len(snake_case_						)						)

											__lowercase 					=   outputs.attentions

											self.assertEqual(len(snake_case_						) ,       self.model_tester.num_hidden_layers						)
											self.assertListEqual(
											    list(self_attentions[0].shape[-3:]						) ,       [self.model_tester.num_attention_heads, seq_len, seq_len] ,       )






					def A      (				self						)   ->			Tuple:







								'''simple docstring'''

								def check_hidden_states_output(snake_case_ ,       snake_case_ ,       snake_case_						):
											__lowercase 					=   model_class(snake_case_						)
											model.to(snake_case_						)
											model.eval()

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

											__lowercase 					=   outputs.hidden_states

											__lowercase 					=   getattr(
											    self.model_tester ,       '''expected_num_hidden_layers''' ,       self.model_tester.num_hidden_layers + 1						)
											self.assertEqual(len(snake_case_						) ,       snake_case_						)

											# YOLOS has a different seq_length
											__lowercase 					=   self.model_tester.expected_seq_len

											self.assertListEqual(
											    list(hidden_states[0].shape[-2:]						) ,       [seq_length, self.model_tester.hidden_size] ,       )

								__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(snake_case_ ,       snake_case_ ,       snake_case_						)

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

											check_hidden_states_output(snake_case_ ,       snake_case_ ,       snake_case_						)






					def A      (				self						)   ->			str:







								'''simple docstring'''

								__lowercase 					=   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*snake_case_						)






					@slow
					def A      (				self						)   ->			Union[str, Any]:







								'''simple docstring'''

								for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowercase 					=   YolosModel.from_pretrained(snake_case_						)
											self.assertIsNotNone(snake_case_						)




def 		lowercase_  (     ):


			'''simple docstring'''







			__lowercase 					=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
			return image





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



					'''simple docstring'''







					@cached_property
					def A      (				self						)   ->			Optional[int]:







								'''simple docstring'''

								return AutoImageProcessor.from_pretrained('''hustvl/yolos-small'''						) if is_vision_available() else None






					@slow
					def A      (				self						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''						).to(snake_case_						)

								__lowercase 					=   self.default_image_processor
								__lowercase 					=   prepare_img()
								__lowercase 					=   image_processor(images=snake_case_ ,       return_tensors='''pt'''						).to(snake_case_						)

								# forward pass
								with torch.no_grad():
											__lowercase 					=   model(inputs.pixel_values						)

								# verify outputs
								__lowercase 					=   torch.Size((1, 1_0_0, 9_2)						)
								self.assertEqual(outputs.logits.shape ,       snake_case_						)

								__lowercase 					=   torch.tensor(
								    [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]] ,       device=snake_case_ ,       )
								__lowercase 					=   torch.tensor(
								    [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]] ,       device=snake_case_						)
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] ,       snake_case_ ,       atol=1e-4						)						)
								self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] ,       snake_case_ ,       atol=1e-4						)						)

								# verify postprocessing
								__lowercase 					=   image_processor.post_process_object_detection(
								    snake_case_ ,       threshold=0.3 ,       target_sizes=[image.size[::-1]]						)[0]
								__lowercase 					=   torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]						).to(snake_case_						)
								__lowercase 					=   [7_5, 7_5, 1_7, 6_3, 1_7]
								__lowercase 					=   torch.tensor([3_3_5.0_6_0_9, 7_9.3_8_4_8, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5]						).to(snake_case_						)

								self.assertEqual(len(results['''scores''']						) ,       5						)
								self.assertTrue(torch.allclose(results['''scores'''] ,       snake_case_ ,       atol=1e-4						)						)
								self.assertSequenceEqual(results['''labels'''].tolist() ,       snake_case_						)
								self.assertTrue(torch.allclose(results['''boxes'''][0, :] ,       snake_case_						)						)






def 		lowercase_  (     _UpperCamelCase       ,			_UpperCamelCase  ):


			'''simple docstring'''







			return price * (1 + tax_rate)


if __name__ == "__main__":
	print(f'''{price_plus_tax(100, 0.25) = }''')
	print(f'''{price_plus_tax(125.50, 0.05) = }''')


