

"""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     __a   :

			"""simple docstring"""

			def __init__(							self     :					List[str]						,  lowercase_     :					List[str]						,  lowercase_     :					int=False						,  lowercase_     :					int=13						,  lowercase_     :					Optional[int]=(32, 128)						,  lowercase_     :					Optional[int]=4						,  lowercase_     :					List[Any]=3						,  lowercase_     :					Optional[int]=27						,  lowercase_     :					int=38						,  lowercase_     :					Optional[int]=99						,  lowercase_     :					Tuple=99						,  lowercase_     :					Optional[int]=32						,  lowercase_     :					List[Any]=5						,  lowercase_     :					Optional[Any]=4						,  lowercase_     :					Optional[Any]=4.0						,  lowercase_     :					Optional[int]=257						,  lowercase_     :					Tuple=None						,  ):
								UpperCamelCase__		:    int         =parent
								UpperCamelCase__		:    int         =is_training
								UpperCamelCase__		:    Optional[int]         =batch_size
								UpperCamelCase__		:    Any         =image_size
								UpperCamelCase__		:    List[Any]         =patch_size
								UpperCamelCase__		:    str         =num_channels
								UpperCamelCase__		:    List[str]         =max_token_length
								UpperCamelCase__		:    List[str]         =num_character_labels
								UpperCamelCase__		:    Dict         =num_bpe_labels
								UpperCamelCase__		:    Union[str, Any]         =num_wordpiece_labels
								UpperCamelCase__		:    Optional[Any]         =hidden_size
								UpperCamelCase__		:    Tuple         =num_hidden_layers
								UpperCamelCase__		:    List[str]         =num_attention_heads
								UpperCamelCase__		:    str         =mlp_ratio
								UpperCamelCase__		:    Tuple         =patch_embeds_hidden_size
								UpperCamelCase__		:    int         =output_hidden_states






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






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								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    _lowerCAmelCase			(							self     :					Union[str, Any]						,  lowercase_     :					Union[str, Any]						,  lowercase_     :					List[Any]						):
								UpperCamelCase__		:    List[str]         =MgpstrForSceneTextRecognition(lowercase_						)
								model.to(lowercase_						)
								model.eval()
								with torch.no_grad():
													UpperCamelCase__		:    Union[str, Any]         =model(lowercase_						)
								self.parent.assertEqual(
								    generated_ids[0][0].shape						,  (self.batch_size, self.max_token_length, self.num_character_labels)						)






			def    _lowerCAmelCase			(							self     :					Tuple						):
								UpperCamelCase__		:    Any         =self.prepare_config_and_inputs()
								UpperCamelCase__		:    Optional[int]         =config_and_inputs
								UpperCamelCase__		:    str         ={'pixel_values': pixel_values}
								return config, inputs_dict



@require_torch
class     __a   (      a_,    a_,    unittest.TestCase    ):

			"""simple docstring"""

			SCREAMING_SNAKE_CASE_						     =						(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
			SCREAMING_SNAKE_CASE_						     =						{'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
			SCREAMING_SNAKE_CASE_						     =						False

			SCREAMING_SNAKE_CASE_						     =						False
			SCREAMING_SNAKE_CASE_						     =						False
			SCREAMING_SNAKE_CASE_						     =						False
			SCREAMING_SNAKE_CASE_						     =						False






			def    _lowerCAmelCase			(							self     :					Dict						):
								UpperCamelCase__		:    Union[str, Any]         =MgpstrModelTester(self						)
								UpperCamelCase__		:    Tuple         =ConfigTester(self						,  config_class=lowercase_						,  has_text_modality=lowercase_						)






			def    _lowerCAmelCase			(							self     :					List[Any]						):
								self.config_tester.run_common_tests()






			def    _lowerCAmelCase			(							self     :					int						):
								UpperCamelCase__		:    str         =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowercase_						)






			@unittest.skip(reason='''MgpstrModel does not use inputs_embeds'''						)
			def    _lowerCAmelCase			(							self     :					Tuple						):
								pass






			def    _lowerCAmelCase			(							self     :					Dict						):
								UpperCamelCase__		:    Tuple         =self.model_tester.prepare_config_and_inputs_for_common()

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






			def    _lowerCAmelCase			(							self     :					List[Any]						):
								UpperCamelCase__		:    Tuple         =self.model_tester.prepare_config_and_inputs_for_common()

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

													UpperCamelCase__		:    Optional[Any]         =['pixel_values']
													self.assertListEqual(arg_names[:1]						,  lowercase_						)






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






			def    _lowerCAmelCase			(							self     :					str						):
								UpperCamelCase__		:    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

													UpperCamelCase__		:    Dict         =True
													UpperCamelCase__		:    Optional[int]         =model_class(lowercase_						)
													self.assertTrue(model.is_gradient_checkpointing						)






			def    _lowerCAmelCase			(							self     :					Tuple						):
								def check_hidden_states_output(lowercase_     :					int						,  lowercase_     :					Optional[Any]						,  lowercase_     :					Optional[int]						):
													UpperCamelCase__		:    Dict         =model_class(lowercase_						)
													model.to(lowercase_						)
													model.eval()

													with torch.no_grad():
																		UpperCamelCase__		:    int         =model(**self._prepare_for_class(lowercase_						,  lowercase_						)						)

													UpperCamelCase__		:    int         =outputs.hidden_states

													UpperCamelCase__		:    int         =getattr(
													    self.model_tester						,  '''expected_num_hidden_layers'''						,  self.model_tester.num_hidden_layers + 1						)
													self.assertEqual(len(lowercase_						)						,  lowercase_						)

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

								UpperCamelCase__		:    Any         =self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													UpperCamelCase__		:    str         =True
													check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_						)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													UpperCamelCase__		:    str         =True

													check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_						)






			def    _lowerCAmelCase			(							self     :					List[Any]						):
								UpperCamelCase__		:    Union[str, Any]         =self.model_tester.prepare_config_and_inputs_for_common()

								UpperCamelCase__		:    Optional[Any]         =_config_zero_init(lowercase_						)
								for model_class in self.all_model_classes:
													UpperCamelCase__		:    Union[str, Any]         =model_class(config=lowercase_						)
													for name, param in model.named_parameters():
																		if isinstance(lowercase_						,  (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    _lowerCAmelCase			(							self     :					List[str]						):
								pass



def        _lowerCAmelCase      (						):


					'''simple docstring'''






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







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

			"""simple docstring"""

			@slow
			def    _lowerCAmelCase			(							self     :					Dict						):
								UpperCamelCase__		:    str         ='alibaba-damo/mgp-str-base'
								UpperCamelCase__		:    Optional[Any]         =MgpstrForSceneTextRecognition.from_pretrained(lowercase_						).to(lowercase_						)
								UpperCamelCase__		:    int         =MgpstrProcessor.from_pretrained(lowercase_						)

								UpperCamelCase__		:    Tuple         =prepare_img()
								UpperCamelCase__		:    List[str]         =processor(images=lowercase_						,  return_tensors='''pt'''						).pixel_values.to(lowercase_						)

								# forward pass
								with torch.no_grad():
													UpperCamelCase__		:    Tuple         =model(lowercase_						)

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

								UpperCamelCase__		:    str         =processor.batch_decode(outputs.logits						)
								UpperCamelCase__		:    Dict         ='ticket'

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

								UpperCamelCase__		:    Optional[int]         =torch.tensor(
								    [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]						,  device=lowercase_						,  )

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





"""simple docstring"""





import unittest

from transformers.image_processing_utils import get_size_dict

class     __a   (      unittest.TestCase    ):

			"""simple docstring"""

			def    _lowerCAmelCase			(							self     :					Dict						):
								# Test a dict with the wrong keys raises an error
								UpperCamelCase__		:    str         ={'''wrong_key''': 224}
								with self.assertRaises(lowercase_						):
													get_size_dict(lowercase_						)

								UpperCamelCase__		:    Any         ={'''height''': 224}
								with self.assertRaises(lowercase_						):
													get_size_dict(lowercase_						)

								UpperCamelCase__		:    List[str]         ={'''width''': 224, '''shortest_edge''': 224}
								with self.assertRaises(lowercase_						):
													get_size_dict(lowercase_						)

								# Test a dict with the correct keys is returned as is
								UpperCamelCase__		:    int         ={'''height''': 224, '''width''': 224}
								UpperCamelCase__		:    str         =get_size_dict(lowercase_						)
								self.assertEqual(lowercase_						,  lowercase_						)

								UpperCamelCase__		:    List[Any]         ={'''shortest_edge''': 224}
								UpperCamelCase__		:    List[str]         =get_size_dict(lowercase_						)
								self.assertEqual(lowercase_						,  {'''shortest_edge''': 224}						)

								UpperCamelCase__		:    List[Any]         ={'''longest_edge''': 224, '''shortest_edge''': 224}
								UpperCamelCase__		:    Tuple         =get_size_dict(lowercase_						)
								self.assertEqual(lowercase_						,  {'''longest_edge''': 224, '''shortest_edge''': 224}						)

								# Test a single int value which  represents (size, size)
								UpperCamelCase__		:    Optional[int]         =get_size_dict(224						)
								self.assertEqual(lowercase_						,  {'''height''': 224, '''width''': 224}						)

								# Test a single int value which represents the shortest edge
								UpperCamelCase__		:    str         =get_size_dict(224						,  default_to_square=lowercase_						)
								self.assertEqual(lowercase_						,  {'''shortest_edge''': 224}						)

								# Test a tuple of ints which represents (height, width)
								UpperCamelCase__		:    List[str]         =get_size_dict((150, 200)						)
								self.assertEqual(lowercase_						,  {'''height''': 150, '''width''': 200}						)

								# Test a tuple of ints which represents (width, height)
								UpperCamelCase__		:    Optional[int]         =get_size_dict((150, 200)						,  height_width_order=lowercase_						)
								self.assertEqual(lowercase_						,  {'''height''': 200, '''width''': 150}						)

								# Test an int representing the shortest edge and max_size which represents the longest edge
								UpperCamelCase__		:    int         =get_size_dict(224						,  max_size=256						,  default_to_square=lowercase_						)
								self.assertEqual(lowercase_						,  {'''shortest_edge''': 224, '''longest_edge''': 256}						)

								# Test int with default_to_square=True and max_size fails
								with self.assertRaises(lowercase_						):
													get_size_dict(224						,  max_size=256						,  default_to_square=lowercase_						)


