



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





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



       '''simple docstring'''







       snake_case   :							Union[str, Any]						  =parent
       snake_case   :							int						  =is_training
       snake_case   :							Dict						  =batch_size
       snake_case   :							Union[str, Any]						  =image_size
       snake_case   :							str						  =patch_size
       snake_case   :							int						  =num_channels
       snake_case   :							Optional[int]						  =max_token_length
       snake_case   :							List[Any]						  =num_character_labels
       snake_case   :							Tuple						  =num_bpe_labels
       snake_case   :							Optional[int]						  =num_wordpiece_labels
       snake_case   :							str						  =hidden_size
       snake_case   :							Optional[int]						  =num_hidden_layers
       snake_case   :							int						  =num_attention_heads
       snake_case   :							Union[str, Any]						  =mlp_ratio
       snake_case   :							Dict						  =patch_embeds_hidden_size
       snake_case   :							Dict						  =output_hidden_states





    def 					__snake_case       (    self    :    str     ):



       '''simple docstring'''







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





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''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 					__snake_case       (    self    :    Dict,    _snake_case    :    List[str],    _snake_case    :    Tuple     ):



       '''simple docstring'''







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






    def 					__snake_case       (    self    :    List[Any]     ):



       '''simple docstring'''







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





@require_torch
class 							lowerCAmelCase_		(	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 					__snake_case       (    self    :    List[Any]     ):



       '''simple docstring'''







       snake_case   :							Dict						  =MgpstrModelTester(self     )
       snake_case   :							Dict						  =ConfigTester(self,    config_class=_snake_case,    has_text_modality=_snake_case     )





    def 					__snake_case       (    self    :    Union[str, Any]     ):



       '''simple docstring'''







       self.config_tester.run_common_tests()





    def 					__snake_case       (    self    :    Optional[Any]     ):



       '''simple docstring'''







       snake_case   :							int						  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_snake_case     )





    @unittest.skip(reason='''MgpstrModel does not use inputs_embeds'''     )
    def 					__snake_case       (    self    :    List[str]     ):



       '''simple docstring'''







       pass





    def 					__snake_case       (    self    :    List[Any]     ):



       '''simple docstring'''







       snake_case  ,    snake_case   :							Any						  =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          snake_case   :							Optional[Any]						  =model_class(_snake_case     )
          self.assertIsInstance(model.get_input_embeddings(),    (nn.Module)     )
          snake_case   :							Optional[int]						  =model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(_snake_case,    nn.Linear     )     )





    def 					__snake_case       (    self    :    int     ):



       '''simple docstring'''







       snake_case  ,    snake_case   :							Any						  =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          snake_case   :							Union[str, Any]						  =model_class(_snake_case     )
          snake_case   :							Optional[Any]						  =inspect.signature(model.forward     )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          snake_case   :							List[str]						  =[*signature.parameters.keys()]

          snake_case   :							List[str]						  =['''pixel_values''']
          self.assertListEqual(arg_names[:1],    _snake_case     )





    @unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''     )
    def 					__snake_case       (    self    :    Union[str, Any]     ):



       '''simple docstring'''







       pass





    def 					__snake_case       (    self    :    Optional[Any]     ):



       '''simple docstring'''







       snake_case  ,    snake_case   :							Tuple						  =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

          snake_case   :							Dict						  =True
          snake_case   :							str						  =model_class(_snake_case     )
          self.assertTrue(model.is_gradient_checkpointing     )





    def 					__snake_case       (    self    :    List[str]     ):



       '''simple docstring'''







       def check_hidden_states_output(_snake_case    :    Optional[int],    _snake_case    :    Tuple,    _snake_case    :    Optional[Any]     ):
          snake_case   :							str						  =model_class(_snake_case     )
          model.to(_snake_case     )
          model.eval()

          with torch.no_grad():
             snake_case   :							Optional[Any]						  =model(**self._prepare_for_class(_snake_case,    _snake_case     )     )

          snake_case   :							Optional[int]						  =outputs.hidden_states

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

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

       snake_case  ,    snake_case   :							Dict						  =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          snake_case   :							Union[str, Any]						  =True
          check_hidden_states_output(_snake_case,    _snake_case,    _snake_case     )

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

          check_hidden_states_output(_snake_case,    _snake_case,    _snake_case     )





    def 					__snake_case       (    self    :    str     ):



       '''simple docstring'''







       snake_case  ,    snake_case   :							Tuple						  =self.model_tester.prepare_config_and_inputs_for_common()

       snake_case   :							List[Any]						  =_config_zero_init(_snake_case     )
       for model_class in self.all_model_classes:
          snake_case   :							str						  =model_class(config=_snake_case     )
          for name, param in model.named_parameters():
             if isinstance(_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 					__snake_case       (    self    :    Optional[Any]     ):



       '''simple docstring'''







       pass




def 		_a   (  ):
   snake_case   :							Tuple						  ='''https://i.postimg.cc/ZKwLg2Gw/367-14.png'''
   snake_case   :							Union[str, Any]						  =Image.open(requests.get(lowerCamelCase_					,						stream=lowerCamelCase_							).raw							).convert('''RGB'''							)
   return im





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





    @slow
    def 					__snake_case       (    self    :    str     ):



       '''simple docstring'''







       snake_case   :							Dict						  ='''alibaba-damo/mgp-str-base'''
       snake_case   :							List[Any]						  =MgpstrForSceneTextRecognition.from_pretrained(_snake_case     ).to(_snake_case     )
       snake_case   :							Optional[int]						  =MgpstrProcessor.from_pretrained(_snake_case     )

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

       # forward pass
       with torch.no_grad():
          snake_case   :							Tuple						  =model(_snake_case     )

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

       snake_case   :							Optional[Any]						  =processor.batch_decode(outputs.logits     )
       snake_case   :							List[str]						  ='''ticket'''

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

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

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










'''simple docstring'''





from __future__ import annotations

import random
import string





class 							lowerCAmelCase_		:





    def __init__(    self    :    Union[str, Any],    _snake_case    :    str | None = None     ):



       '''simple docstring'''







       snake_case   :							Optional[int]						  =passcode or self.__passcode_creator()
       snake_case   :							List[str]						  =self.__make_key_list()
       snake_case   :							Dict						  =self.__make_shift_key()





    def __str__(    self    :    List[Any]     ):



       '''simple docstring'''







       return "".join(self.__passcode     )





    def 					__snake_case       (    self    :    int,    _snake_case    :    list[int]     ):



       '''simple docstring'''







       for i in range(1,    len(_snake_case     ),    2     ):
          iterlist[i] *= -1
       return iterlist





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       snake_case   :							int						  =string.ascii_letters + string.digits
       snake_case   :							Union[str, Any]						  =[random.choice(_snake_case     ) for _ in range(random.randint(10,    20     )     )]
       return password





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       snake_case   :							Dict						  =(
           string.ascii_letters + string.digits + string.punctuation + ''' \t\n'''
       )

       snake_case   :							Any						  =[]

       # creates points known as breakpoints to break the key_list_options at those
       # points and pivot each substring
       snake_case   :							Optional[int]						  =sorted(set(self.__passcode     )     )
       snake_case   :							list[str]						  =[]

       # algorithm for creating a new shuffled list, keys_l, out of key_list_options
       for i in key_list_options:
          temp_list.extend(_snake_case     )

          # checking breakpoints at which to pivot temporary sublist and add it into
          # keys_l
          if i in breakpoints or i == key_list_options[-1]:
             keys_l.extend(temp_list[::-1]     )
             temp_list.clear()

        # returning a shuffled keys_l to prevent brute force guessing of shift key
       return keys_l





    def 					__snake_case       (    self    :    Union[str, Any]     ):



       '''simple docstring'''







       snake_case   :							str						  =sum(self.__neg_pos([ord(_snake_case     ) for x in self.__passcode]     )     )
       return num if num > 0 else len(self.__passcode     )





    def 					__snake_case       (    self    :    Optional[int],    _snake_case    :    str     ):



       '''simple docstring'''







       snake_case   :							List[Any]						  =''''''

       # decoding shift like Caesar cipher algorithm implementing negative shift or
       # reverse shift or left shift
       for i in encoded_message:
          snake_case   :							Optional[int]						  =self.__key_list.index(_snake_case     )
          decoded_message += self.__key_list[
              (position - self.__shift_key) % -len(self.__key_list     )
          ]

       return decoded_message






    def 					__snake_case       (    self    :    Union[str, Any],    _snake_case    :    str     ):



       '''simple docstring'''







       snake_case   :							int						  =''''''

       # encoding shift like Caesar cipher algorithm implementing positive shift or
       # forward shift or right shift
       for i in plaintext:
          snake_case   :							int						  =self.__key_list.index(_snake_case     )
          encoded_message += self.__key_list[
              (position + self.__shift_key) % len(self.__key_list     )
          ]

       return encoded_message




def 		_a   (  lowerCamelCase_ = "Hello, this is a modified Caesar cipher"							):
   snake_case   :							List[Any]						  =ShuffledShiftCipher()
   return cipa.decrypt(cipa.encrypt(lowerCamelCase_							)							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()





