

'''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 		lowerCAmelCase__     :



 """simple docstring"""



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


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   parent
      __SCREAMING_SNAKE_CASE						     =   is_training
      __SCREAMING_SNAKE_CASE						     =   batch_size
      __SCREAMING_SNAKE_CASE						     =   image_size
      __SCREAMING_SNAKE_CASE						     =   patch_size
      __SCREAMING_SNAKE_CASE						     =   num_channels
      __SCREAMING_SNAKE_CASE						     =   max_token_length
      __SCREAMING_SNAKE_CASE						     =   num_character_labels
      __SCREAMING_SNAKE_CASE						     =   num_bpe_labels
      __SCREAMING_SNAKE_CASE						     =   num_wordpiece_labels
      __SCREAMING_SNAKE_CASE						     =   hidden_size
      __SCREAMING_SNAKE_CASE						     =   num_hidden_layers
      __SCREAMING_SNAKE_CASE						     =   num_attention_heads
      __SCREAMING_SNAKE_CASE						     =   mlp_ratio
      __SCREAMING_SNAKE_CASE						     =   patch_embeds_hidden_size
      __SCREAMING_SNAKE_CASE						     =   output_hidden_states
 def    UpperCAmelCase__	(	self      : Dict    )						->				List[str]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]    )
      __SCREAMING_SNAKE_CASE						     =   self.get_config()
      return config, pixel_values
 def    UpperCAmelCase__	(	self      : Dict    )						->				Dict:


      """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    UpperCAmelCase__	(	self      : Any      ,							__SCREAMING_SNAKE_CASE      : Dict      ,							__SCREAMING_SNAKE_CASE      : Tuple    )						->				List[str]:


      """simple docstring"""




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


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


      """simple docstring"""




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







@require_torch
class 		lowerCAmelCase__     (   a				,      a				,      unittest.TestCase      ):



 """simple docstring"""



 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    UpperCAmelCase__	(	self      : int    )						->				Optional[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   MgpstrModelTester(self    )
      __SCREAMING_SNAKE_CASE						     =   ConfigTester(self      ,							config_class=__SCREAMING_SNAKE_CASE      ,							has_text_modality=__SCREAMING_SNAKE_CASE    )
 def    UpperCAmelCase__	(	self      : Dict    )						->				Union[str, Any]:


      """simple docstring"""




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


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE    )
 @unittest.skip(reason="""MgpstrModel does not use inputs_embeds"""    )
 def    UpperCAmelCase__	(	self      : Dict    )						->				Any:


      """simple docstring"""




      pass
 def    UpperCAmelCase__	(	self      : List[Any]    )						->				Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     ,    __SCREAMING_SNAKE_CASE						     =   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           __SCREAMING_SNAKE_CASE						     =   model_class(__SCREAMING_SNAKE_CASE    )
           self.assertIsInstance(model.get_input_embeddings()      ,							(nn.Module)    )
           __SCREAMING_SNAKE_CASE						     =   model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE      ,							nn.Linear    )    )
 def    UpperCAmelCase__	(	self      : List[Any]    )						->				Tuple:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     ,    __SCREAMING_SNAKE_CASE						     =   self.model_tester.prepare_config_and_inputs_for_common()

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

           __SCREAMING_SNAKE_CASE						     =   ["""pixel_values"""]
           self.assertListEqual(arg_names[:1]      ,							__SCREAMING_SNAKE_CASE    )
 @unittest.skip(reason="""MgpstrModel does not support feedforward chunking"""    )
 def    UpperCAmelCase__	(	self      : str    )						->				List[Any]:


      """simple docstring"""




      pass
 def    UpperCAmelCase__	(	self      : Union[str, Any]    )						->				List[Any]:


      """simple docstring"""




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

           __SCREAMING_SNAKE_CASE						     =   True
           __SCREAMING_SNAKE_CASE						     =   model_class(__SCREAMING_SNAKE_CASE    )
           self.assertTrue(model.is_gradient_checkpointing    )
 def    UpperCAmelCase__	(	self      : Optional[int]    )						->				Optional[Any]:


      """simple docstring"""




      def check_hidden_states_output(__SCREAMING_SNAKE_CASE      : Any      ,							__SCREAMING_SNAKE_CASE      : Tuple      ,							__SCREAMING_SNAKE_CASE      : Union[str, Any]    ):
           __SCREAMING_SNAKE_CASE						     =   model_class(__SCREAMING_SNAKE_CASE    )
           model.to(__SCREAMING_SNAKE_CASE    )
           model.eval()

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

           __SCREAMING_SNAKE_CASE						     =   outputs.hidden_states

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

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

      __SCREAMING_SNAKE_CASE     ,    __SCREAMING_SNAKE_CASE						     =   self.model_tester.prepare_config_and_inputs_for_common()

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

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

           check_hidden_states_output(__SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE    )
 def    UpperCAmelCase__	(	self      : Optional[int]    )						->				Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     ,    __SCREAMING_SNAKE_CASE						     =   self.model_tester.prepare_config_and_inputs_for_common()

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


      """simple docstring"""




      pass







def      a__ (						):




     """simple docstring"""


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







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



 """simple docstring"""



 @slow
 def    UpperCAmelCase__	(	self      : List[str]    )						->				Optional[int]:


      """simple docstring"""




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

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

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

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

      __SCREAMING_SNAKE_CASE						     =   processor.batch_decode(outputs.logits    )
      __SCREAMING_SNAKE_CASE						     =   """ticket"""

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

      __SCREAMING_SNAKE_CASE						     =   torch.tensor(
          [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]      ,							device=__SCREAMING_SNAKE_CASE      ,							)

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









'''simple docstring'''



def      a__ (						):




     """simple docstring"""


     __SCREAMING_SNAKE_CASE						     =   1

     while True:
          if (
              sorted(str(a__		)		)
              == sorted(str(2 * i		)		)
              == sorted(str(3 * i		)		)
              == sorted(str(4 * i		)		)
              == sorted(str(5 * i		)		)
              == sorted(str(6 * i		)		)
          ):
               return i

          i += 1


if __name__ == "__main__":
  print(solution())






