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




					def __init__(       self   ,	__UpperCamelCase   ,	__UpperCamelCase=False   ,	__UpperCamelCase=13   ,	__UpperCamelCase=(32, 128)   ,	__UpperCamelCase=4   ,	__UpperCamelCase=3   ,	__UpperCamelCase=27   ,	__UpperCamelCase=38   ,	__UpperCamelCase=99   ,	__UpperCamelCase=99   ,	__UpperCamelCase=32   ,	__UpperCamelCase=5   ,	__UpperCamelCase=4   ,	__UpperCamelCase=4.0   ,	__UpperCamelCase=257   ,	__UpperCamelCase=None   ,	)					->  Optional[int]:



									'''simple docstring'''







									snake_case__ :     str 							=				parent
									snake_case__ :     Optional[Any] 							=				is_training
									snake_case__ :     int 							=				batch_size
									snake_case__ :     str 							=				image_size
									snake_case__ :     List[Any] 							=				patch_size
									snake_case__ :     str 							=				num_channels
									snake_case__ :     Optional[Any] 							=				max_token_length
									snake_case__ :     str 							=				num_character_labels
									snake_case__ :     Tuple 							=				num_bpe_labels
									snake_case__ :     List[str] 							=				num_wordpiece_labels
									snake_case__ :     Any 							=				hidden_size
									snake_case__ :     Optional[Any] 							=				num_hidden_layers
									snake_case__ :     Union[str, Any] 							=				num_attention_heads
									snake_case__ :     List[str] 							=				mlp_ratio
									snake_case__ :     Tuple 							=				patch_embeds_hidden_size
									snake_case__ :     List[Any] 							=				output_hidden_states




					def       __a      (       self		)					->  Tuple:



									'''simple docstring'''







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




					def       __a      (       self		)					->  int:



									'''simple docstring'''







									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       __a      (       self   ,	__UpperCamelCase   ,	__UpperCamelCase		)					->  Tuple:



									'''simple docstring'''







									snake_case__ :     Tuple 							=				MgpstrForSceneTextRecognition(__UpperCamelCase		)
									model.to(__UpperCamelCase		)
									model.eval()
									with torch.no_grad():
													snake_case__ :     Any 							=				model(__UpperCamelCase		)
									self.parent.assertEqual(
									    generated_ids[0][0].shape   ,	(self.batch_size, self.max_token_length, self.num_character_labels)		)




					def       __a      (       self		)					->  List[str]:



									'''simple docstring'''







									snake_case__ :     List[Any] 							=				self.prepare_config_and_inputs()
									snake_case__ :     List[Any] 							=				config_and_inputs
									snake_case__ :     Optional[int] 							=				{'pixel_values': pixel_values}
									return config, inputs_dict





@require_torch
class 			__snake_case  (      _lowerCamelCase   ,_lowerCamelCase   ,unittest.TestCase     ):
					__lowerCamelCase	 =       (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
					__lowerCamelCase	 =       {"""feature-extraction""": MgpstrForSceneTextRecognition} if is_torch_available() else {}
					__lowerCamelCase	 =       False

					__lowerCamelCase	 =       False
					__lowerCamelCase	 =       False
					__lowerCamelCase	 =       False
					__lowerCamelCase	 =       False




					def       __a      (       self		)					->  int:



									'''simple docstring'''







									snake_case__ :     int 							=				MgpstrModelTester(self		)
									snake_case__ :     Any 							=				ConfigTester(self   ,	config_class=__UpperCamelCase   ,	has_text_modality=__UpperCamelCase		)




					def       __a      (       self		)					->  int:



									'''simple docstring'''







									self.config_tester.run_common_tests()




					def       __a      (       self		)					->  str:



									'''simple docstring'''







									snake_case__ :     Union[str, Any] 							=				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       __a      (       self		)					->  Any:



									'''simple docstring'''







									pass




					def       __a      (       self		)					->  Optional[Any]:



									'''simple docstring'''







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

									for model_class in self.all_model_classes:
													snake_case__ :     Optional[Any] 							=				model_class(__UpperCamelCase		)
													self.assertIsInstance(model.get_input_embeddings()   ,	(nn.Module)		)
													snake_case__ :     Dict 							=				model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(__UpperCamelCase   ,	nn.Linear		)		)




					def       __a      (       self		)					->  Tuple:



									'''simple docstring'''







									snake_case__ :     Dict 							=				self.model_tester.prepare_config_and_inputs_for_common()

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

													snake_case__ :     List[Any] 							=				['pixel_values']
													self.assertListEqual(arg_names[:1]   ,	__UpperCamelCase		)




					@unittest.skip(reason='MgpstrModel does not support feedforward chunking'		)
					def       __a      (       self		)					->  int:



									'''simple docstring'''







									pass




					def       __a      (       self		)					->  Tuple:



									'''simple docstring'''







									snake_case__ :     Optional[int] 							=				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

													snake_case__ :     int 							=				True
													snake_case__ :     Dict 							=				model_class(__UpperCamelCase		)
													self.assertTrue(model.is_gradient_checkpointing		)




					def       __a      (       self		)					->  List[str]:



									'''simple docstring'''







									def check_hidden_states_output(__UpperCamelCase   ,	__UpperCamelCase   ,	__UpperCamelCase		):
													snake_case__ :     Tuple 							=				model_class(__UpperCamelCase		)
													model.to(__UpperCamelCase		)
													model.eval()

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

													snake_case__ :     Any 							=				outputs.hidden_states

													snake_case__ :     str 							=				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]   ,	)

									snake_case__ :     Union[str, Any] 							=				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													snake_case__ :     Any 							=				True
													check_hidden_states_output(__UpperCamelCase   ,	__UpperCamelCase   ,	__UpperCamelCase		)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													snake_case__ :     Optional[Any] 							=				True

													check_hidden_states_output(__UpperCamelCase   ,	__UpperCamelCase   ,	__UpperCamelCase		)




					def       __a      (       self		)					->  Any:



									'''simple docstring'''







									snake_case__ :     Tuple 							=				self.model_tester.prepare_config_and_inputs_for_common()

									snake_case__ :     Any 							=				_config_zero_init(__UpperCamelCase		)
									for model_class in self.all_model_classes:
													snake_case__ :     Tuple 							=				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       __a      (       self		)					->  int:



									'''simple docstring'''







									pass




def 			UpperCamelCase__						(    )       -> List[Any]:
				snake_case__ :     int 							=				'https://i.postimg.cc/ZKwLg2Gw/367-14.png'
				snake_case__ :     List[str] 							=				Image.open(requests.get(A__      ,			stream=A__   ).raw   ).convert('RGB'   )
				return im





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




					@slow
					def       __a      (       self		)					->  Optional[Any]:



									'''simple docstring'''







									snake_case__ :     Tuple 							=				'alibaba-damo/mgp-str-base'
									snake_case__ :     Optional[int] 							=				MgpstrForSceneTextRecognition.from_pretrained(__UpperCamelCase		).to(__UpperCamelCase		)
									snake_case__ :     Tuple 							=				MgpstrProcessor.from_pretrained(__UpperCamelCase		)

									snake_case__ :     int 							=				prepare_img()
									snake_case__ :     Dict 							=				processor(images=__UpperCamelCase   ,	return_tensors='pt'		).pixel_values.to(__UpperCamelCase		)

									# forward pass
									with torch.no_grad():
													snake_case__ :     Optional[Any] 							=				model(__UpperCamelCase		)

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

									snake_case__ :     List[Any] 							=				processor.batch_decode(outputs.logits		)
									snake_case__ :     Union[str, Any] 							=				'ticket'

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

									snake_case__ :     Union[str, Any] 							=				torch.tensor(
									    [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]   ,	device=__UpperCamelCase   ,	)

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



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available


lowerCAmelCase__					:       Optional[int]		=       {}

try:
				if not is_sentencepiece_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				lowerCAmelCase__					:       Tuple		=       ['''MBart50Tokenizer''']

try:
				if not is_tokenizers_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				lowerCAmelCase__					:       Tuple		=       ['''MBart50TokenizerFast''']


if TYPE_CHECKING:
				try:
								if not is_sentencepiece_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_mbartaa import MBartaaTokenizer

				try:
								if not is_tokenizers_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_mbartaa_fast import MBartaaTokenizerFast

else:
				import sys

				lowerCAmelCase__					:       Optional[int]		=       _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


