


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


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





      '''simple docstring'''






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


     def   UpperCAmelCase__						(   self				:  Tuple      )	->   Tuple:





      '''simple docstring'''






      UpperCamelCase__       :     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   UpperCAmelCase__						(   self				:  Any      )	->   List[str]:





      '''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				:  Union[str, Any]				,						lowerCamelCase__				:  Tuple				,						lowerCamelCase__				:  str      )	->   List[Any]:





      '''simple docstring'''






      UpperCamelCase__       :     int 							= MgpstrForSceneTextRecognition(_SCREAMING_SNAKE_CASE      )
      model.to(_SCREAMING_SNAKE_CASE      )
      model.eval()
      with torch.no_grad():
       UpperCamelCase__       :     Any 							= 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				:  Optional[int]      )	->   Optional[Any]:





      '''simple docstring'''






      UpperCamelCase__       :     int 							= self.prepare_config_and_inputs()
      UpperCamelCase__							,					UpperCamelCase__       :     List[Any] 							= config_and_inputs
      UpperCamelCase__       :     Union[str, Any] 							= {'''pixel_values''': pixel_values}
      return config, inputs_dict



@require_torch
class    __magic_name__						(  lowerCAmelCase__       ,					lowerCAmelCase__       ,					unittest.TestCase):
     A:		Any								=   (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
     A:		Any								=   {"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
     A:		Optional[Any]								=   False

     A:		str								=   False
     A:		Optional[Any]								=   False
     A:		Union[str, Any]								=   False
     A:		Any								=   False


     def   UpperCAmelCase__						(   self				:  Optional[int]      )	->   List[Any]:





      '''simple docstring'''






      UpperCamelCase__       :     Any 							= MgpstrModelTester(self      )
      UpperCamelCase__       :     List[str] 							= ConfigTester(self				,						config_class=_SCREAMING_SNAKE_CASE				,						has_text_modality=_SCREAMING_SNAKE_CASE      )


     def   UpperCAmelCase__						(   self				:  Optional[int]      )	->   int:





      '''simple docstring'''






      self.config_tester.run_common_tests()


     def   UpperCAmelCase__						(   self				:  List[Any]      )	->   List[Any]:





      '''simple docstring'''






      UpperCamelCase__       :     List[Any] 							= 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				:  Any      )	->   Optional[Any]:





      '''simple docstring'''






      pass


     def   UpperCAmelCase__						(   self				:  Optional[Any]      )	->   Optional[Any]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     List[str] 							= self.model_tester.prepare_config_and_inputs_for_common()

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


     def   UpperCAmelCase__						(   self				:  Optional[Any]      )	->   Dict:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     List[str] 							= self.model_tester.prepare_config_and_inputs_for_common()

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

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


     @unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''      )
     def   UpperCAmelCase__						(   self				:  str      )	->   List[str]:





      '''simple docstring'''






      pass


     def   UpperCAmelCase__						(   self				:  List[Any]      )	->   Optional[Any]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Optional[Any] 							= 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__       :     List[str] 							= True
       UpperCamelCase__       :     List[str] 							= model_class(_SCREAMING_SNAKE_CASE      )
       self.assertTrue(model.is_gradient_checkpointing      )


     def   UpperCAmelCase__						(   self				:  List[Any]      )	->   Optional[Any]:





      '''simple docstring'''






      def check_hidden_states_output(lowerCamelCase__				:  List[str]				,						lowerCamelCase__				:  Union[str, Any]				,						lowerCamelCase__				:  Optional[Any]      ):
       UpperCamelCase__       :     List[Any] 							= model_class(_SCREAMING_SNAKE_CASE      )
       model.to(_SCREAMING_SNAKE_CASE      )
       model.eval()

       with torch.no_grad():
        UpperCamelCase__       :     List[str] 							= model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE      )      )

       UpperCamelCase__       :     List[str] 							= outputs.hidden_states

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

      UpperCamelCase__							,					UpperCamelCase__       :     Optional[Any] 							= self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       UpperCamelCase__       :     Tuple 							= 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"]
       UpperCamelCase__       :     List[Any] 							= True

       check_hidden_states_output(_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE      )


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





      '''simple docstring'''






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

      UpperCamelCase__       :     Tuple 							= _config_zero_init(_SCREAMING_SNAKE_CASE      )
      for model_class in self.all_model_classes:
       UpperCamelCase__       :     List[str] 							= 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				:  List[Any]      )	->   List[Any]:





      '''simple docstring'''






      pass



def       _a	(					):







 """simple docstring"""



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






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


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





      '''simple docstring'''






      UpperCamelCase__       :     Optional[Any] 							= '''alibaba-damo/mgp-str-base'''
      UpperCamelCase__       :     str 							= MgpstrForSceneTextRecognition.from_pretrained(_SCREAMING_SNAKE_CASE      ).to(_SCREAMING_SNAKE_CASE      )
      UpperCamelCase__       :     List[str] 							= MgpstrProcessor.from_pretrained(_SCREAMING_SNAKE_CASE      )

      UpperCamelCase__       :     List[Any] 							= prepare_img()
      UpperCamelCase__       :     Dict 							= processor(images=_SCREAMING_SNAKE_CASE				,						return_tensors='''pt'''      ).pixel_values.to(_SCREAMING_SNAKE_CASE      )

      # forward pass
      with torch.no_grad():
       UpperCamelCase__       :     Optional[Any] 							= model(_SCREAMING_SNAKE_CASE      )

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

      UpperCamelCase__       :     Optional[int] 							= processor.batch_decode(outputs.logits      )
      UpperCamelCase__       :     Union[str, Any] 							= '''ticket'''

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

      UpperCamelCase__       :     Optional[Any] 							= 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      )      )





from math import factorial




def        __UpperCamelCase     (      _A					:							Union[str, Any]      ,  _A					:							Tuple		)				->Any:



							"""simple docstring"""
							return factorial(_A		) / (factorial(_A		) * factorial(n - r		))




def        __UpperCamelCase     (      )				->Any:



							"""simple docstring"""
							lowerCamelCase_								=0

							for i in range(1      ,  101		):
														for j in range(1      ,  i + 1		):
																					if combinations(_A      ,  _A		) > 1E6:
																												total += 1
							return total


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