





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      A_	:
	def __init__(   self							, _A							, _A=False							, _A=1_3							, _A=(3_2, 1_2_8)							, _A=4							, _A=3							, _A=2_7							, _A=3_8							, _A=9_9							, _A=9_9							, _A=3_2							, _A=5							, _A=4							, _A=4.0							, _A=2_5_7							, _A=None							, ):






				'''simple docstring'''







				UpperCAmelCase       		=    parent
				UpperCAmelCase       		=    is_training
				UpperCAmelCase       		=    batch_size
				UpperCAmelCase       		=    image_size
				UpperCAmelCase       		=    patch_size
				UpperCAmelCase       		=    num_channels
				UpperCAmelCase       		=    max_token_length
				UpperCAmelCase       		=    num_character_labels
				UpperCAmelCase       		=    num_bpe_labels
				UpperCAmelCase       		=    num_wordpiece_labels
				UpperCAmelCase       		=    hidden_size
				UpperCAmelCase       		=    num_hidden_layers
				UpperCAmelCase       		=    num_attention_heads
				UpperCAmelCase       		=    mlp_ratio
				UpperCAmelCase       		=    patch_embeds_hidden_size
				UpperCAmelCase       		=    output_hidden_states
	def 					_lowercase    (   self		):






				'''simple docstring'''







				UpperCAmelCase       		=    floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]		)
				UpperCAmelCase       		=    self.get_config()
				return config, pixel_values
	def 					_lowercase    (   self		):






				'''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 					_lowercase    (   self							, _A							, _A		):






				'''simple docstring'''







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







	def 					_lowercase    (   self		):






				'''simple docstring'''







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

@require_torch
class      A_	(a_					,							a_					,							unittest.TestCase      ):
	UpperCAmelCase__ =      (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
	UpperCAmelCase__ =      {'''feature-extraction''': MgpstrForSceneTextRecognition} if is_torch_available() else {}
	UpperCAmelCase__ =      False

	UpperCAmelCase__ =      False
	UpperCAmelCase__ =      False
	UpperCAmelCase__ =      False
	UpperCAmelCase__ =      False
	def 					_lowercase    (   self		):






				'''simple docstring'''







				UpperCAmelCase       		=    MgpstrModelTester(self		)
				UpperCAmelCase       		=    ConfigTester(self							, config_class=_A							, has_text_modality=_A		)
	def 					_lowercase    (   self		):






				'''simple docstring'''







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






				'''simple docstring'''







				UpperCAmelCase       		=    self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_A		)
	@unittest.skip(reason='''MgpstrModel does not use inputs_embeds'''		)
	def 					_lowercase    (   self		):






				'''simple docstring'''







				pass
	def 					_lowercase    (   self		):






				'''simple docstring'''







				UpperCAmelCase		,      UpperCAmelCase       		=    self.model_tester.prepare_config_and_inputs_for_common()

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






				'''simple docstring'''







				UpperCAmelCase		,      UpperCAmelCase       		=    self.model_tester.prepare_config_and_inputs_for_common()

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

							UpperCAmelCase       		=    ['''pixel_values''']
							self.assertListEqual(arg_names[:1]							, _A		)
	@unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''		)
	def 					_lowercase    (   self		):






				'''simple docstring'''







				pass
	def 					_lowercase    (   self		):






				'''simple docstring'''







				UpperCAmelCase		,      UpperCAmelCase       		=    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

							UpperCAmelCase       		=    True
							UpperCAmelCase       		=    model_class(_A		)
							self.assertTrue(model.is_gradient_checkpointing		)
	def 					_lowercase    (   self		):






				'''simple docstring'''







				def check_hidden_states_output(_A							, _A							, _A		):
							UpperCAmelCase       		=    model_class(_A		)
							model.to(_A		)
							model.eval()

							with torch.no_grad():
										UpperCAmelCase       		=    model(**self._prepare_for_class(_A							, _A		)		)

							UpperCAmelCase       		=    outputs.hidden_states

							UpperCAmelCase       		=    getattr(
							    self.model_tester							, '''expected_num_hidden_layers'''							, self.model_tester.num_hidden_layers + 1		)
							self.assertEqual(len(_A		)							, _A		)

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

				UpperCAmelCase		,      UpperCAmelCase       		=    self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							UpperCAmelCase       		=    True
							check_hidden_states_output(_A							, _A							, _A		)

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

							check_hidden_states_output(_A							, _A							, _A		)
	def 					_lowercase    (   self		):






				'''simple docstring'''







				UpperCAmelCase		,      UpperCAmelCase       		=    self.model_tester.prepare_config_and_inputs_for_common()

				UpperCAmelCase       		=    _config_zero_init(_A		)
				for model_class in self.all_model_classes:
							UpperCAmelCase       		=    model_class(config=_A		)
							for name, param in model.named_parameters():
										if isinstance(_A							, (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 					_lowercase    (   self		):






				'''simple docstring'''







				pass





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







			'''simple docstring'''

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






@require_vision
@require_torch
class      A_	(unittest.TestCase      ):
	@slow
	def 					_lowercase    (   self		):






				'''simple docstring'''







				UpperCAmelCase       		=    '''alibaba-damo/mgp-str-base'''
				UpperCAmelCase       		=    MgpstrForSceneTextRecognition.from_pretrained(_A		).to(_A		)
				UpperCAmelCase       		=    MgpstrProcessor.from_pretrained(_A		)

				UpperCAmelCase       		=    prepare_img()
				UpperCAmelCase       		=    processor(images=_A							, return_tensors='''pt'''		).pixel_values.to(_A		)

				# forward pass
				with torch.no_grad():
							UpperCAmelCase       		=    model(_A		)

				# verify the logits
				self.assertEqual(outputs.logits[0].shape							, torch.Size((1, 2_7, 3_8)		)		)

				UpperCAmelCase       		=    processor.batch_decode(outputs.logits		)
				UpperCAmelCase       		=    '''ticket'''

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

				UpperCAmelCase       		=    torch.tensor(
				    [[[-39.53_97, -44.40_24, -36.18_44], [-61.47_09, -63.86_39, -58.34_54], [-74.02_25, -68.54_94, -71.21_64]]]							, device=_A							, )

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










def 						__SCREAMING_SNAKE_CASE  (    UpperCamelCase__      ,      UpperCamelCase__      ,      UpperCamelCase__			)  ->    float:







			'''simple docstring'''

			if mass < 0:
						raise ValueError('''The mass of the body cannot be negative'''			)
			if radius <= 0:
						raise ValueError('''The radius is always a positive non zero integer'''			)
			return (mass * (velocity) ** 2) / radius


if __name__ == "__main__":
				import doctest

				doctest.testmod(verbose=True)



