





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     ,   __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     ,   )    ->	Dict:
							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 						snake_case_		(    self							)    ->	Optional[Any]:
							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 						snake_case_		(    self							)    ->	Dict:
							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     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	List[str]:
							UpperCamelCase__								=						MgpstrForSceneTextRecognition(__lowerCamelCase							)
							model.to(__lowerCamelCase							)
							model.eval()
							with torch.no_grad():
									UpperCamelCase__								=						model(__lowerCamelCase							)
							self.parent.assertEqual(
							    generated_ids[0][0].shape     ,   (self.batch_size, self.max_token_length, self.num_character_labels)							)




					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							UpperCamelCase__								=						self.prepare_config_and_inputs()
							UpperCamelCase__								=						config_and_inputs
							UpperCamelCase__								=						{'pixel_values': pixel_values}
							return config, inputs_dict




@require_torch
class 	_UpperCAmelCase						( A_			,							A_			,							unittest.TestCase       ):
					__A        = (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
					__A        = {"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
					__A        = False

					__A        = False
					__A        = False
					__A        = False
					__A        = False




					def 						snake_case_		(    self							)    ->	int:
							UpperCamelCase__								=						MgpstrModelTester(self							)
							UpperCamelCase__								=						ConfigTester(self     ,   config_class=__lowerCamelCase     ,   has_text_modality=__lowerCamelCase							)




					def 						snake_case_		(    self							)    ->	Optional[int]:
							self.config_tester.run_common_tests()




					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							UpperCamelCase__								=						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 						snake_case_		(    self							)    ->	Optional[Any]:
							pass




					def 						snake_case_		(    self							)    ->	List[str]:
							UpperCamelCase__								=						self.model_tester.prepare_config_and_inputs_for_common()

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




					def 						snake_case_		(    self							)    ->	int:
							UpperCamelCase__								=						self.model_tester.prepare_config_and_inputs_for_common()

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




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




					def 						snake_case_		(    self							)    ->	Tuple:
							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(__lowerCamelCase							)
									self.assertTrue(model.is_gradient_checkpointing							)




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



							def check_hidden_states_output(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase							):
									UpperCamelCase__								=						model_class(__lowerCamelCase							)
									model.to(__lowerCamelCase							)
									model.eval()

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

									UpperCamelCase__								=						outputs.hidden_states

									UpperCamelCase__								=						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]     ,   )

							UpperCamelCase__								=						self.model_tester.prepare_config_and_inputs_for_common()

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

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

									check_hidden_states_output(__lowerCamelCase     ,   __lowerCamelCase     ,   __lowerCamelCase							)




					def 						snake_case_		(    self							)    ->	int:
							UpperCamelCase__								=						self.model_tester.prepare_config_and_inputs_for_common()

							UpperCamelCase__								=						_config_zero_init(__lowerCamelCase							)
							for model_class in self.all_model_classes:
									UpperCamelCase__								=						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 						snake_case_		(    self							)    ->	Dict:
							pass



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




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




					@slow
					def 						snake_case_		(    self							)    ->	List[Any]:
							UpperCamelCase__								=						'alibaba-damo/mgp-str-base'
							UpperCamelCase__								=						MgpstrForSceneTextRecognition.from_pretrained(__lowerCamelCase							).to(__lowerCamelCase							)
							UpperCamelCase__								=						MgpstrProcessor.from_pretrained(__lowerCamelCase							)

							UpperCamelCase__								=						prepare_img()
							UpperCamelCase__								=						processor(images=__lowerCamelCase     ,   return_tensors="""pt"""							).pixel_values.to(__lowerCamelCase							)

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

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

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

							self.assertEqual(out_strs["""generated_text"""][0]     ,   __lowerCamelCase							)

							UpperCamelCase__								=						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							)							)






"""simple docstring"""







def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				list[int]						)    ->     tuple[int, int]:







     '''simple docstring'''


     if len(_SCREAMING_SNAKE_CASE						) == 1:
          return a[0], a[0]
     else:
          # split A into half.
          __A					:					List[str]								=		a[: len(_SCREAMING_SNAKE_CASE						) // 2]
          __A					:					Optional[Any]								=		a[len(_SCREAMING_SNAKE_CASE						) // 2 :]

          # 2 sub problems, 1/2 of original size.
          __A						,		__A					:					int								=		max_difference(_SCREAMING_SNAKE_CASE						)
          __A						,		__A					:					str								=		max_difference(_SCREAMING_SNAKE_CASE						)

          # get min of first and max of second
          # linear time
          __A					:					str								=		min(_SCREAMING_SNAKE_CASE						)
          __A					:					Optional[int]								=		max(_SCREAMING_SNAKE_CASE						)

          # 3 cases, either (small1, big1),
          # (min_first, max_second), (small2, big2)
          # constant comparisons
          if biga - smalla > max_second - min_first and biga - smalla > biga - smalla:
               return smalla, biga
          elif biga - smalla > max_second - min_first:
               return smalla, biga
          else:
               return min_first, max_second


if __name__ == "__main__":
       import doctest

       doctest.testmod()



