"""simple docstring"""




import inspect
import unittest

import requests

from transformers import MgpstrConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import MgpstrForSceneTextRecognition


if is_vision_available():
				from PIL import Image

				from transformers import MgpstrProcessor
class      UpperCamelCase__:





						def __init__(							self		,__UpperCAmelCase		,__UpperCAmelCase=False		,__UpperCAmelCase=13		,__UpperCAmelCase=(32, 1_28)		,__UpperCAmelCase=4		,__UpperCAmelCase=3		,__UpperCAmelCase=27		,__UpperCAmelCase=38		,__UpperCAmelCase=99		,__UpperCAmelCase=99		,__UpperCAmelCase=32		,__UpperCAmelCase=5		,__UpperCAmelCase=4		,__UpperCAmelCase=4.0		,__UpperCAmelCase=2_57		,__UpperCAmelCase=None		,)       ->					Union[str, Any]:
													A__						  =				parent
													A__						  =				is_training
													A__						  =				batch_size
													A__						  =				image_size
													A__						  =				patch_size
													A__						  =				num_channels
													A__						  =				max_token_length
													A__						  =				num_character_labels
													A__						  =				num_bpe_labels
													A__						  =				num_wordpiece_labels
													A__						  =				hidden_size
													A__						  =				num_hidden_layers
													A__						  =				num_attention_heads
													A__						  =				mlp_ratio
													A__						  =				patch_embeds_hidden_size
													A__						  =				output_hidden_states





						def 					snake_case__						(							self  )       ->					str:
													A__						  =				floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]  )
													A__						  =				self.get_config()
													return config, pixel_values





						def 					snake_case__						(							self  )       ->					Any:
													return MgpstrConfig(
													    image_size=self.image_size		,patch_size=self.patch_size		,num_channels=self.num_channels		,max_token_length=self.max_token_length		,num_character_labels=self.num_character_labels		,num_bpe_labels=self.num_bpe_labels		,num_wordpiece_labels=self.num_wordpiece_labels		,hidden_size=self.hidden_size		,num_hidden_layers=self.num_hidden_layers		,num_attention_heads=self.num_attention_heads		,mlp_ratio=self.mlp_ratio		,output_hidden_states=self.output_hidden_states		,)





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					Optional[Any]:
													A__						  =				MgpstrForSceneTextRecognition(UpperCAmelCase_  )
													model.to(UpperCAmelCase_  )
													model.eval()
													with torch.no_grad():
																				A__						  =				model(UpperCAmelCase_  )
													self.parent.assertEqual(
													    generated_ids[0][0].shape		,(self.batch_size, self.max_token_length, self.num_character_labels)  )





						def 					snake_case__						(							self  )       ->					int:
													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__	:    Tuple    				=		(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
						lowerCAmelCase__	:    Tuple    				=		{'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
						lowerCAmelCase__	:    Optional[int]    				=		False

						lowerCAmelCase__	:    Optional[Any]    				=		False
						lowerCAmelCase__	:    int    				=		False
						lowerCAmelCase__	:    Tuple    				=		False
						lowerCAmelCase__	:    List[Any]    				=		False





						def 					snake_case__						(							self  )       ->					str:
													A__						  =				MgpstrModelTester(self  )
													A__						  =				ConfigTester(self		,config_class=UpperCAmelCase_		,has_text_modality=UpperCAmelCase_  )





						def 					snake_case__						(							self  )       ->					List[Any]:
													self.config_tester.run_common_tests()





						def 					snake_case__						(							self  )       ->					Tuple:
													A__						  =				self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*UpperCAmelCase_  )





						@unittest.skip(reason='MgpstrModel does not use inputs_embeds'  )
						def 					snake_case__						(							self  )       ->					Union[str, Any]:
													pass





						def 					snake_case__						(							self  )       ->					Union[str, Any]:
													A__						  =				self.model_tester.prepare_config_and_inputs_for_common()

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





						def 					snake_case__						(							self  )       ->					str:
													A__						  =				self.model_tester.prepare_config_and_inputs_for_common()

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





						@unittest.skip(reason='MgpstrModel does not support feedforward chunking'  )
						def 					snake_case__						(							self  )       ->					Optional[Any]:
													pass





						def 					snake_case__						(							self  )       ->					Tuple:
													A__						  =				self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				if not model_class.supports_gradient_checkpointing:
																											continue

																				A__						  =				True
																				A__						  =				model_class(UpperCAmelCase_  )
																				self.assertTrue(model.is_gradient_checkpointing  )





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




													def check_hidden_states_output(__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  ):
																				A__						  =				model_class(UpperCAmelCase_  )
																				model.to(UpperCAmelCase_  )
																				model.eval()

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

																				A__						  =				outputs.hidden_states

																				A__						  =				getattr(
																				    self.model_tester		,'expected_num_hidden_layers'		,self.model_tester.num_hidden_layers + 1  )
																				self.assertEqual(len(UpperCAmelCase_  )		,UpperCAmelCase_  )

																				self.assertListEqual(
																				    list(hidden_states[0].shape[-2:]  )		,[self.model_tester.patch_embeds_hidden_size, 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(UpperCAmelCase_		,UpperCAmelCase_		,UpperCAmelCase_  )

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

																				check_hidden_states_output(UpperCAmelCase_		,UpperCAmelCase_		,UpperCAmelCase_  )





						def 					snake_case__						(							self  )       ->					Optional[int]:
													A__						  =				self.model_tester.prepare_config_and_inputs_for_common()

													A__						  =				_config_zero_init(UpperCAmelCase_  )
													for model_class in self.all_model_classes:
																				A__						  =				model_class(config=UpperCAmelCase_  )
																				for name, param in model.named_parameters():
																											if isinstance(UpperCAmelCase_		,(nn.Linear, nn.Convad, nn.LayerNorm)  ):
																																		if param.requires_grad:
																																									self.assertIn(
																																									    ((param.data.mean() * 1e9).round() / 1e9).item()		,[0.0, 1.0]		,msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''		,)





						@unittest.skip(reason='Retain_grad is tested in individual model tests'  )
						def 					snake_case__						(							self  )       ->					Tuple:
													pass






def 	UpperCAmelCase       (						):






							"""simple docstring"""





							A__						  =				"https://i.postimg.cc/ZKwLg2Gw/367-14.png"
							A__						  =				Image.open(requests.get(snake_case_							,     stream=snake_case_					).raw					).convert('RGB'					)
							return im


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





						@slow
						def 					snake_case__						(							self  )       ->					List[str]:
													A__						  =				"alibaba-damo/mgp-str-base"
													A__						  =				MgpstrForSceneTextRecognition.from_pretrained(UpperCAmelCase_  ).to(UpperCAmelCase_  )
													A__						  =				MgpstrProcessor.from_pretrained(UpperCAmelCase_  )

													A__						  =				prepare_img()
													A__						  =				processor(images=UpperCAmelCase_		,return_tensors='pt'  ).pixel_values.to(UpperCAmelCase_  )

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

													# verify the logits
													self.assertEqual(outputs.logits[0].shape		,torch.Size((1, 27, 38)  )  )

													A__						  =				processor.batch_decode(outputs.logits  )
													A__						  =				"ticket"

													self.assertEqual(out_strs['generated_text'][0]		,UpperCAmelCase_  )

													A__						  =				torch.tensor(
													    [[[-3_9.5_3_9_7, -4_4.4_0_2_4, -3_6.1_8_4_4], [-6_1.4_7_0_9, -6_3.8_6_3_9, -5_8.3_4_5_4], [-7_4.0_2_2_5, -6_8.5_4_9_4, -7_1.2_1_6_4]]]		,device=UpperCAmelCase_		,)

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













"""simple docstring"""





import doctest

import projectq
from projectq.ops import H, Measure






def 							A(    snake_case_						):
       """simple docstring"""





       lowercase__:							Dict         =     quantum_engine.allocate_qubit()
       H | qubit
       Measure | qubit
       return int(snake_case_						)


if __name__ == "__main__":
  doctest.testmod()

  # initialises a new quantum backend
  UpperCamelCase					=     projectq.MainEngine()

  # Generate a list of 10 random numbers
  UpperCamelCase					=     [get_random_number(quantum_engine) for _ in range(10)]

  # Flushes the quantum engine from memory
  quantum_engine.flush()

  print("""Random numbers""", random_numbers_list)






