



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







	'''simple docstring'''




	def __init__(	self   ,       lowerCamelCase   ,       lowerCamelCase=False   ,       lowerCamelCase=13   ,       lowerCamelCase=(32, 128)   ,       lowerCamelCase=4   ,       lowerCamelCase=3   ,       lowerCamelCase=27   ,       lowerCamelCase=38   ,       lowerCamelCase=99   ,       lowerCamelCase=99   ,       lowerCamelCase=32   ,       lowerCamelCase=5   ,       lowerCamelCase=4   ,       lowerCamelCase=4.0   ,       lowerCamelCase=257   ,       lowerCamelCase=None   ,       ):



				'''simple docstring'''


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



				'''simple docstring'''


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



				'''simple docstring'''


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







	def 				_A			(	self       ):



				'''simple docstring'''


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


@require_torch
class lowerCAmelCase_       (   A_ ,A_ ,unittest.TestCase			):







	'''simple docstring'''




	A_       :     Optional[int]									=		(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
	A_       :     str									=		{'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
	A_       :     Union[str, Any]									=		False

	A_       :     Tuple									=		False
	A_       :     int									=		False
	A_       :     Optional[int]									=		False
	A_       :     Any									=		False

	def 				_A			(	self       ):



				'''simple docstring'''


				a__					=  MgpstrModelTester(self       )
				a__					=  ConfigTester(self   ,       config_class=lowerCamelCase   ,       has_text_modality=lowerCamelCase       )

	def 				_A			(	self       ):



				'''simple docstring'''


				self.config_tester.run_common_tests()

	def 				_A			(	self       ):



				'''simple docstring'''


				a__					=  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowerCamelCase       )

	@unittest.skip(reason="""MgpstrModel does not use inputs_embeds"""       )
	def 				_A			(	self       ):



				'''simple docstring'''


				pass

	def 				_A			(	self       ):



				'''simple docstring'''


				a__				,       a__					=  self.model_tester.prepare_config_and_inputs_for_common()

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

	def 				_A			(	self       ):



				'''simple docstring'''


				a__				,       a__					=  self.model_tester.prepare_config_and_inputs_for_common()

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

	@unittest.skip(reason="""MgpstrModel does not support feedforward chunking"""       )
	def 				_A			(	self       ):



				'''simple docstring'''


				pass

	def 				_A			(	self       ):



				'''simple docstring'''


				a__				,       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(lowerCamelCase       )
							self.assertTrue(model.is_gradient_checkpointing       )

	def 				_A			(	self       ):



				'''simple docstring'''


				def check_hidden_states_output(lowerCamelCase   ,       lowerCamelCase   ,       lowerCamelCase       ):
							a__					=  model_class(lowerCamelCase       )
							model.to(lowerCamelCase       )
							model.eval()

							with torch.no_grad():
										a__					=  model(**self._prepare_for_class(lowerCamelCase   ,       lowerCamelCase       )       )

							a__					=  outputs.hidden_states

							a__					=  getattr(
							    self.model_tester   ,       """expected_num_hidden_layers"""   ,       self.model_tester.num_hidden_layers + 1       )
							self.assertEqual(len(lowerCamelCase       )   ,       lowerCamelCase       )

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

				a__				,       a__					=  self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							a__					=  True
							check_hidden_states_output(lowerCamelCase   ,       lowerCamelCase   ,       lowerCamelCase       )

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

							check_hidden_states_output(lowerCamelCase   ,       lowerCamelCase   ,       lowerCamelCase       )

	def 				_A			(	self       ):



				'''simple docstring'''


				a__				,       a__					=  self.model_tester.prepare_config_and_inputs_for_common()

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



				'''simple docstring'''


				pass




def    UpperCAmelCase					(  ):



			'''simple docstring'''





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





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







	'''simple docstring'''




	@slow
	def 				_A			(	self       ):



				'''simple docstring'''


				a__					=  """alibaba-damo/mgp-str-base"""
				a__					=  MgpstrForSceneTextRecognition.from_pretrained(lowerCamelCase       ).to(lowerCamelCase       )
				a__					=  MgpstrProcessor.from_pretrained(lowerCamelCase       )

				a__					=  prepare_img()
				a__					=  processor(images=lowerCamelCase   ,       return_tensors="""pt"""       ).pixel_values.to(lowerCamelCase       )

				# forward pass
				with torch.no_grad():
							a__					=  model(lowerCamelCase       )

				# 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]   ,       lowerCamelCase       )

				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=lowerCamelCase   ,       )

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






from typing import TYPE_CHECKING

from ...utils import _LazyModule


_lowercase				:					List[Any]     					={"""tokenization_bert_japanese""": ["""BertJapaneseTokenizer""", """CharacterTokenizer""", """MecabTokenizer"""]}


if TYPE_CHECKING:
	from .tokenization_bert_japanese import BertJapaneseTokenizer, CharacterTokenizer, MecabTokenizer

else:
	import sys

	_lowercase				:					Union[str, Any]     					=_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

