
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      UpperCamelCase    :



	def __init__(       self			,	UpperCAmelCase__			,	UpperCAmelCase__=13			,	UpperCAmelCase__=[30, 30]			,	UpperCAmelCase__=2			,	UpperCAmelCase__=3			,	UpperCAmelCase__=True			,	UpperCAmelCase__=True			,	UpperCAmelCase__=32			,	UpperCAmelCase__=5			,	UpperCAmelCase__=4			,	UpperCAmelCase__=37			,	UpperCAmelCase__="gelu"			,	UpperCAmelCase__=0.1			,	UpperCAmelCase__=0.1			,	UpperCAmelCase__=10			,	UpperCAmelCase__=0.02			,	UpperCAmelCase__=3			,	UpperCAmelCase__=None			,	UpperCAmelCase__=8			,	UpperCAmelCase__=10			,	):
							A__							=       parent
							A__							=       batch_size
							A__							=       image_size
							A__							=       patch_size
							A__							=       num_channels
							A__							=       is_training
							A__							=       use_labels
							A__							=       hidden_size
							A__							=       num_hidden_layers
							A__							=       num_attention_heads
							A__							=       intermediate_size
							A__							=       hidden_act
							A__							=       hidden_dropout_prob
							A__							=       attention_probs_dropout_prob
							A__							=       type_sequence_label_size
							A__							=       initializer_range
							A__							=       num_labels
							A__							=       scope
							A__							=       n_targets
							A__							=       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
							A__							=       (image_size[1] // patch_size) * (image_size[0] // patch_size)
							A__							=       num_patches + 1 + self.num_detection_tokens



	def 			__A							(       self		):
							A__							=       floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]		)

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

							A__							=       self.get_config()

							return config, pixel_values, labels



	def 			__A							(       self		):
							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=_a			,	initializer_range=self.initializer_range			,	num_detection_tokens=self.num_detection_tokens			,	num_labels=self.num_labels			,	)



	def 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__		):
							A__							=       YolosModel(config=_a		)
							model.to(_a		)
							model.eval()
							A__							=       model(_a		)
							self.parent.assertEqual(
							    result.last_hidden_state.shape			,	(self.batch_size, self.expected_seq_len, self.hidden_size)		)



	def 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__		):
							A__							=       YolosForObjectDetection(_a		)
							model.to(_a		)
							model.eval()

							A__							=       model(pixel_values=_a		)
							A__							=       model(_a		)

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

							A__							=       model(pixel_values=_a			,	labels=_a		)

							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		):
							A__							=       self.prepare_config_and_inputs()
							A__							=       config_and_inputs
							A__							=       {'pixel_values': pixel_values}
							return config, inputs_dict






@require_torch
class      UpperCamelCase    (						lowercase__       ,    lowercase__       ,    unittest.TestCase     ):
	lowerCAmelCase	:   Any				=	(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
	lowerCAmelCase	:   List[Any]				=	(
	    {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
	)

	lowerCAmelCase	:   Optional[int]				=	False
	lowerCAmelCase	:   Union[str, Any]				=	False
	lowerCAmelCase	:   Optional[int]				=	False
	lowerCAmelCase	:   Dict				=	False



	def 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__=False		):
							A__							=       super()._prepare_for_class(_a			,	_a			,	return_labels=_a		)

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

							return inputs_dict



	def 			__A							(       self		):
							A__							=       YolosModelTester(self		)
							A__							=       ConfigTester(self			,	config_class=_a			,	has_text_modality=_a			,	hidden_size=37		)



	def 			__A							(       self		):
							self.config_tester.run_common_tests()



	def 			__A							(       self		):
							pass



	def 			__A							(       self		):
							A__							=       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													A__							=       model_class(_a		)
													self.assertIsInstance(model.get_input_embeddings()			,	(nn.Module)		)
													A__							=       model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_a			,	nn.Linear		)		)



	def 			__A							(       self		):
							A__							=       self.model_tester.prepare_config_and_inputs_for_common()

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

													A__							=       ['pixel_values']
													self.assertListEqual(arg_names[:1]			,	_a		)



	def 			__A							(       self		):
							A__							=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_a		)



	def 			__A							(       self		):
							A__							=       self.model_tester.prepare_config_and_inputs_for_common()
							A__							=       True

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

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

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

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

													A__							=       1
													self.assertEqual(out_len + added_hidden_states			,	len(_a		)		)

													A__							=       outputs.attentions

													self.assertEqual(len(_a		)			,	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		):






							def check_hidden_states_output(UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__		):
													A__							=       model_class(_a		)
													model.to(_a		)
													model.eval()

													with torch.no_grad():
																			A__							=       model(**self._prepare_for_class(_a			,	_a		)		)

													A__							=       outputs.hidden_states

													A__							=       getattr(
													    self.model_tester			,	"expected_num_hidden_layers"			,	self.model_tester.num_hidden_layers + 1		)
													self.assertEqual(len(_a		)			,	_a		)

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

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

							A__							=       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													A__							=       True
													check_hidden_states_output(_a			,	_a			,	_a		)

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

													check_hidden_states_output(_a			,	_a			,	_a		)



	def 			__A							(       self		):
							A__							=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_object_detection(*_a		)



	@slow
	def 			__A							(       self		):






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





def  UpperCamelCase						(       )->       List[Any]:





						"""simple docstring"""





						A__							=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
						return image






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



	@cached_property
	def 			__A							(       self		):
							return AutoImageProcessor.from_pretrained("hustvl/yolos-small"		) if is_vision_available() else None



	@slow
	def 			__A							(       self		):
							A__							=       YolosForObjectDetection.from_pretrained("hustvl/yolos-small"		).to(_a		)

							A__							=       self.default_image_processor
							A__							=       prepare_img()
							A__							=       image_processor(images=_a			,	return_tensors="pt"		).to(_a		)

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

							# verify outputs
							A__							=       torch.Size((1, 100, 92)		)
							self.assertEqual(outputs.logits.shape			,	_a		)

							A__							=       torch.tensor(
							    [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]]			,	device=_a			,	)
							A__							=       torch.tensor(
							    [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]]			,	device=_a		)
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]			,	_a			,	atol=1e-4		)		)
							self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]			,	_a			,	atol=1e-4		)		)

							# verify postprocessing
							A__							=       image_processor.post_process_object_detection(
							    _a			,	threshold=0.3			,	target_sizes=[image.size[::-1]]		)[0]
							A__							=       torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]		).to(_a		)
							A__							=       [75, 75, 17, 63, 17]
							A__							=       torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]		).to(_a		)

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










import argparse
import struct
import unittest






class      UpperCamelCase    :



	def __init__(       self			,	UpperCAmelCase__		):
							A__							=       data

							# Initialize hash values
							A__							=       [
							    0x6A_09E_667,
							    0xBB_67A_E85,
							    0x3C_6EF_372,
							    0xA5_4FF_53A,
							    0x51_0E5_27F,
							    0x9B_056_88C,
							    0x1F_83D_9AB,
							    0x5B_E0C_D19,
							]

							# Initialize round constants
							A__							=       [
							    0x42_8A2_F98,
							    0x71_374_491,
							    0xB5_C0F_BCF,
							    0xE9_B5D_BA5,
							    0x39_56C_25B,
							    0x59_F11_1F1,
							    0x92_3F8_2A4,
							    0xAB_1C5_ED5,
							    0xD8_07A_A98,
							    0x12_835_B01,
							    0x24_318_5BE,
							    0x55_0C7_DC3,
							    0x72_BE5_D74,
							    0x80_DEB_1FE,
							    0x9B_DC0_6A7,
							    0xC1_9BF_174,
							    0xE4_9B6_9C1,
							    0xEF_BE4_786,
							    0x0F_C19_DC6,
							    0x24_0CA_1CC,
							    0x2D_E92_C6F,
							    0x4A_748_4AA,
							    0x5C_B0A_9DC,
							    0x76_F98_8DA,
							    0x98_3E5_152,
							    0xA8_31C_66D,
							    0xB0_032_7C8,
							    0xBF_597_FC7,
							    0xC6_E00_BF3,
							    0xD5_A79_147,
							    0x06_CA6_351,
							    0x14_292_967,
							    0x27_B70_A85,
							    0x2E_1B2_138,
							    0x4D_2C6_DFC,
							    0x53_380_D13,
							    0x65_0A7_354,
							    0x76_6A0_ABB,
							    0x81_C2C_92E,
							    0x92_722_C85,
							    0xA2_BFE_8A1,
							    0xA8_1A6_64B,
							    0xC2_4B8_B70,
							    0xC7_6C5_1A3,
							    0xD1_92E_819,
							    0xD6_990_624,
							    0xF4_0E3_585,
							    0x10_6AA_070,
							    0x19_A4C_116,
							    0x1E_376_C08,
							    0x27_487_74C,
							    0x34_B0B_CB5,
							    0x39_1C0_CB3,
							    0x4E_D8A_A4A,
							    0x5B_9CC_A4F,
							    0x68_2E6_FF3,
							    0x74_8F8_2EE,
							    0x78_A56_36F,
							    0x84_C87_814,
							    0x8C_C70_208,
							    0x90_BEF_FFA,
							    0xA4_506_CEB,
							    0xBE_F9A_3F7,
							    0xC6_717_8F2,
							]

							A__							=       self.preprocessing(self.data		)
							self.final_hash()



	@staticmethod
	def 			__A							(       UpperCAmelCase__		):
							A__							=       b"\x80" + (b"\x00" * (63 - (len(UpperCAmelCase__		) + 8) % 64))
							A__							=       struct.pack(">Q"			,	(len(UpperCAmelCase__		) * 8)		)
							return data + padding + big_endian_integer



	def 			__A							(       self		):
							# Convert into blocks of 64 bytes
							A__							=       [
							    self.preprocessed_data[x : x + 64]
							    for x in range(0			,	len(self.preprocessed_data		)			,	64		)
							]

							for block in self.blocks:
													# Convert the given block into a list of 4 byte integers
													A__							=       list(struct.unpack(">16L"			,	UpperCAmelCase__		)		)
													# add 48 0-ed integers
													words += [0] * 48

													A__						,       A__						,       A__						,       A__						,       A__						,       A__						,       A__						,       A__							=       self.hashes

													for index in range(0			,	64		):
																			if index > 15:
																									# modify the zero-ed indexes at the end of the array
																									A__							=       (
																									    self.ror(words[index - 15]			,	7		)
																									    ^ self.ror(words[index - 15]			,	18		)
																									    ^ (words[index - 15] >> 3)
																									)
																									A__							=       (
																									    self.ror(words[index - 2]			,	17		)
																									    ^ self.ror(words[index - 2]			,	19		)
																									    ^ (words[index - 2] >> 10)
																									)

																									A__							=       (
																									    words[index - 16] + sa + words[index - 7] + sa
																									) % 0x100_000_000

																			# Compression
																			A__							=       self.ror(UpperCAmelCase__			,	6		) ^ self.ror(UpperCAmelCase__			,	11		) ^ self.ror(UpperCAmelCase__			,	25		)
																			A__							=       (e & f) ^ ((~e & 0xFF_FFF_FFF) & g)
																			A__							=       (
																			    h + sa + ch + self.round_constants[index] + words[index]
																			) % 0x100_000_000
																			A__							=       self.ror(UpperCAmelCase__			,	2		) ^ self.ror(UpperCAmelCase__			,	13		) ^ self.ror(UpperCAmelCase__			,	22		)
																			A__							=       (a & b) ^ (a & c) ^ (b & c)
																			A__							=       (sa + maj) % 0x100_000_000

																			A__						,       A__						,       A__						,       A__						,       A__						,       A__						,       A__						,       A__							=       (
																			    g,
																			    f,
																			    e,
																			    ((d + tempa) % 0x100_000_000),
																			    c,
																			    b,
																			    a,
																			    ((tempa + tempa) % 0x100_000_000),
																			)

													A__							=       [a, b, c, d, e, f, g, h]

													# Modify final values
													A__							=       [
													    ((element + mutated_hash_values[index]) % 0x100_000_000)
													    for index, element in enumerate(self.hashes		)
													]

							A__							=       "".join([hex(UpperCAmelCase__		)[2:].zfill(8		) for value in self.hashes]		)



	def 			__A							(       self			,	UpperCAmelCase__			,	UpperCAmelCase__		):
							return 0xFF_FFF_FFF & (value << (32 - rotations)) | (value >> rotations)






class      UpperCamelCase    (						unittest.TestCase     ):



	def 			__A							(       self		):
							import hashlib

							A__							=       bytes("Test String"			,	"utf-8"		)
							self.assertEqual(SHAaaa(UpperCAmelCase__		).hash			,	hashlib.shaaaa(UpperCAmelCase__		).hexdigest()		)





def  UpperCamelCase						(       )->       None:





						"""simple docstring"""





						import doctest

						doctest.testmod()

						A__							=       argparse.ArgumentParser()
						parser.add_argument(
						    "-s"			,							"--string"			,							dest="input_string"			,							default="Hello World!! Welcome to Cryptography"			,							help="Hash the string"			,							)
						parser.add_argument(
						    "-f"			,							"--file"			,							dest="input_file"			,							help="Hash contents of a file"    )

						A__							=       parser.parse_args()

						A__							=       args.input_string

						# hash input should be a bytestring
						if args.input_file:
												with open(args.input_file			,							"rb"    ) as f:
																		A__							=       f.read()
						else:
												A__							=       bytes(_A			,							"utf-8"    )

						print(SHAaaa(_A    ).hash    )


if __name__ == "__main__":
						main()





