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







							def __init__(						self  :  List[Any]      ,				snake_case__  :  Union[str, Any]      ,				snake_case__  :  List[Any]=13      ,				snake_case__  :  Optional[Any]=[30, 30]      ,				snake_case__  :  Tuple=2      ,				snake_case__  :  Optional[int]=3      ,				snake_case__  :  Any=True      ,				snake_case__  :  Dict=True      ,				snake_case__  :  List[str]=32      ,				snake_case__  :  List[Any]=5      ,				snake_case__  :  Optional[Any]=4      ,				snake_case__  :  int=37      ,				snake_case__  :  int="gelu"      ,				snake_case__  :  List[str]=0.1      ,				snake_case__  :  Dict=0.1      ,				snake_case__  :  List[Any]=10      ,				snake_case__  :  Any=0.0_2      ,				snake_case__  :  Tuple=3      ,				snake_case__  :  Optional[int]=None      ,				snake_case__  :  Optional[int]=8      ,				snake_case__  :  Tuple=10      ,				):
								"""simple docstring"""







								__lowerCAmelCase         =							parent
								__lowerCAmelCase         =							batch_size
								__lowerCAmelCase         =							image_size
								__lowerCAmelCase         =							patch_size
								__lowerCAmelCase         =							num_channels
								__lowerCAmelCase         =							is_training
								__lowerCAmelCase         =							use_labels
								__lowerCAmelCase         =							hidden_size
								__lowerCAmelCase         =							num_hidden_layers
								__lowerCAmelCase         =							num_attention_heads
								__lowerCAmelCase         =							intermediate_size
								__lowerCAmelCase         =							hidden_act
								__lowerCAmelCase         =							hidden_dropout_prob
								__lowerCAmelCase         =							attention_probs_dropout_prob
								__lowerCAmelCase         =							type_sequence_label_size
								__lowerCAmelCase         =							initializer_range
								__lowerCAmelCase         =							num_labels
								__lowerCAmelCase         =							scope
								__lowerCAmelCase         =							n_targets
								__lowerCAmelCase         =							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
								__lowerCAmelCase         =							(image_size[1] // patch_size) * (image_size[0] // patch_size)
								__lowerCAmelCase         =							num_patches + 1 + self.num_detection_tokens







							def       UpperCAmelCase__					(						self  :  str ):
								"""simple docstring"""







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

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

								__lowerCAmelCase         =							self.get_config()

								return config, pixel_values, labels







							def       UpperCAmelCase__					(						self  :  List[Any] ):
								"""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       UpperCAmelCase__					(						self  :  Optional[Any]      ,				snake_case__  :  List[str]      ,				snake_case__  :  Optional[Any]      ,				snake_case__  :  int ):
								"""simple docstring"""







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







							def       UpperCAmelCase__					(						self  :  Any      ,				snake_case__  :  List[str]      ,				snake_case__  :  List[str]      ,				snake_case__  :  Tuple ):
								"""simple docstring"""







								__lowerCAmelCase         =							YolosForObjectDetection(snake_case__ )
								model.to(snake_case__ )
								model.eval()

								__lowerCAmelCase         =							model(pixel_values=snake_case__ )
								__lowerCAmelCase         =							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) )

								__lowerCAmelCase         =							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       UpperCAmelCase__					(						self  :  Dict ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.prepare_config_and_inputs()
								__lowerCAmelCase   ,						__lowerCAmelCase   ,						__lowerCAmelCase         =							config_and_inputs
								__lowerCAmelCase         =							{"pixel_values": pixel_values}
								return config, inputs_dict

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

							lowercase_		:						str   							=  False
							lowercase_		:						Tuple   							=  False
							lowercase_		:						Optional[Any]   							=  False
							lowercase_		:						Dict   							=  False







							def       UpperCAmelCase__					(						self  :  Optional[int]      ,				snake_case__  :  Optional[Any]      ,				snake_case__  :  Any      ,				snake_case__  :  List[str]=False ):
								"""simple docstring"""







								__lowerCAmelCase         =							super()._prepare_for_class(snake_case__      ,				snake_case__      ,				return_labels=snake_case__ )

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

								return inputs_dict







							def       UpperCAmelCase__					(						self  :  List[Any] ):
								"""simple docstring"""







								__lowerCAmelCase         =							YolosModelTester(self )
								__lowerCAmelCase         =							ConfigTester(self      ,				config_class=snake_case__      ,				has_text_modality=snake_case__      ,				hidden_size=37 )







							def       UpperCAmelCase__					(						self  :  str ):
								"""simple docstring"""







								self.config_tester.run_common_tests()







							def       UpperCAmelCase__					(						self  :  Optional[Any] ):
								"""simple docstring"""







								pass







							def       UpperCAmelCase__					(						self  :  Dict ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.model_tester.prepare_config_and_inputs_for_common()

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







							def       UpperCAmelCase__					(						self  :  Optional[Any] ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.model_tester.prepare_config_and_inputs_for_common()

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

									__lowerCAmelCase         =							["pixel_values"]
									self.assertListEqual(arg_names[:1]      ,				snake_case__ )







							def       UpperCAmelCase__					(						self  :  int ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*snake_case__ )







							def       UpperCAmelCase__					(						self  :  List[Any] ):
								"""simple docstring"""







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

								# in YOLOS, the seq_len is different
								__lowerCAmelCase         =							self.model_tester.expected_seq_len
								for model_class in self.all_model_classes:
									__lowerCAmelCase         =							True
									__lowerCAmelCase         =							False
									__lowerCAmelCase         =							True
									__lowerCAmelCase         =							model_class(snake_case__ )
									model.to(snake_case__ )
									model.eval()
									with torch.no_grad():
										__lowerCAmelCase         =							model(**self._prepare_for_class(snake_case__      ,				snake_case__ ) )
									__lowerCAmelCase         =							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"]
									__lowerCAmelCase         =							True
									__lowerCAmelCase         =							model_class(snake_case__ )
									model.to(snake_case__ )
									model.eval()
									with torch.no_grad():
										__lowerCAmelCase         =							model(**self._prepare_for_class(snake_case__      ,				snake_case__ ) )
									__lowerCAmelCase         =							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]      ,				)
									__lowerCAmelCase         =							len(snake_case__ )

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

									__lowerCAmelCase         =							1
									self.assertEqual(out_len + added_hidden_states      ,				len(snake_case__ ) )

									__lowerCAmelCase         =							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       UpperCAmelCase__					(						self  :  Dict ):
								"""simple docstring"""







								def check_hidden_states_output(snake_case__  :  Union[str, Any]      ,				snake_case__  :  List[Any]      ,				snake_case__  :  Optional[Any] ):
									__lowerCAmelCase         =							model_class(snake_case__ )
									model.to(snake_case__ )
									model.eval()

									with torch.no_grad():
										__lowerCAmelCase         =							model(**self._prepare_for_class(snake_case__      ,				snake_case__ ) )

									__lowerCAmelCase         =							outputs.hidden_states

									__lowerCAmelCase         =							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
									__lowerCAmelCase         =							self.model_tester.expected_seq_len

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

								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									__lowerCAmelCase         =							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"]
									__lowerCAmelCase         =							True

									check_hidden_states_output(snake_case__      ,				snake_case__      ,				snake_case__ )







							def       UpperCAmelCase__					(						self  :  Optional[int] ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*snake_case__ )







							@slow
							def       UpperCAmelCase__					(						self  :  Tuple ):
								"""simple docstring"""







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






def 		_UpperCAmelCase   (	):






	"""simple docstring"""


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







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







							@cached_property
							def       UpperCAmelCase__					(						self  :  Any ):
								"""simple docstring"""







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







							@slow
							def       UpperCAmelCase__					(						self  :  Tuple ):
								"""simple docstring"""







								__lowerCAmelCase         =							YolosForObjectDetection.from_pretrained("hustvl/yolos-small" ).to(snake_case__ )

								__lowerCAmelCase         =							self.default_image_processor
								__lowerCAmelCase         =							prepare_img()
								__lowerCAmelCase         =							image_processor(images=snake_case__      ,				return_tensors="pt" ).to(snake_case__ )

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

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

								__lowerCAmelCase         =							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__      ,				)
								__lowerCAmelCase         =							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
								__lowerCAmelCase         =							image_processor.post_process_object_detection(
								    snake_case__      ,				threshold=0.3      ,				target_sizes=[image.size[::-1]] )[0]
								__lowerCAmelCase         =							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__ )
								__lowerCAmelCase         =							[75, 75, 17, 63, 17]
								__lowerCAmelCase         =							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__ ) )








import numpy as np
import qiskit






def 		_UpperCAmelCase   (	UpperCamelCase:     int = 8			,							UpperCamelCase:     int | None = None  ):






	"""simple docstring"""


	__lowerCAmelCase         =							np.random.default_rng(seed=UpperCamelCase  )

	# Roughly 25% of the qubits will contribute to the key.
	# So we take more than we need.
	__lowerCAmelCase         =							6 * key_len
	# Measurement basis for Alice's qubits.
	__lowerCAmelCase         =							rng.integers(2			,							size=UpperCamelCase  )
	# The set of states Alice will prepare.
	__lowerCAmelCase         =							rng.integers(2			,							size=UpperCamelCase  )
	# Measurement basis for Bob's qubits.
	__lowerCAmelCase         =							rng.integers(2			,							size=UpperCamelCase  )

	# Quantum Circuit to simulate BB84
	__lowerCAmelCase         =							qiskit.QuantumCircuit(UpperCamelCase			,							name="BB84"  )

	# Alice prepares her qubits according to rules above.
	for index, _ in enumerate(UpperCamelCase  ):
		if alice_state[index] == 1:
			bbaa_circ.x(UpperCamelCase  )
		if alice_basis[index] == 1:
			bbaa_circ.h(UpperCamelCase  )
	bbaa_circ.barrier()

	# Bob measures the received qubits according to rules above.
	for index, _ in enumerate(UpperCamelCase  ):
		if bob_basis[index] == 1:
			bbaa_circ.h(UpperCamelCase  )

	bbaa_circ.barrier()
	bbaa_circ.measure_all()

	# Simulate the quantum circuit.
	__lowerCAmelCase         =							qiskit.Aer.get_backend("aer_simulator"  )
	# We only need to run one shot because the key is unique.
	# Multiple shots will produce the same key.
	__lowerCAmelCase         =							qiskit.execute(UpperCamelCase			,							UpperCamelCase			,							shots=1			,							seed_simulator=UpperCamelCase  )
	# Returns the result of measurement.
	__lowerCAmelCase         =							job.result().get_counts(UpperCamelCase  ).most_frequent()

	# Extracting the generated key from the simulation results.
	# Only keep measurement results where Alice and Bob chose the same basis.
	__lowerCAmelCase         =							"".join(
	    [
	        result_bit
	        for alice_basis_bit, bob_basis_bit, result_bit in zip(
	            UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase  )
	        if alice_basis_bit == bob_basis_bit
	    ]  )

	# Get final key. Pad with 0 if too short, otherwise truncate.
	__lowerCAmelCase         =							gen_key[:key_len] if len(UpperCamelCase  ) >= key_len else gen_key.ljust(UpperCamelCase			,							"0"  )
	return key


if __name__ == "__main__":
					print(f'''The generated key is : {bbaa(8, seed=0)}''')
					from doctest import testmod

					testmod()






