



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				:				int ,	__lowerCAmelCase				:				Optional[int] ,	__lowerCAmelCase				:				Dict=False ,	__lowerCAmelCase				:				int=13 ,	__lowerCAmelCase				:				Union[str, Any]=(32, 1_28) ,	__lowerCAmelCase				:				int=4 ,	__lowerCAmelCase				:				List[Any]=3 ,	__lowerCAmelCase				:				List[str]=27 ,	__lowerCAmelCase				:				List[str]=38 ,	__lowerCAmelCase				:				Union[str, Any]=99 ,	__lowerCAmelCase				:				int=99 ,	__lowerCAmelCase				:				int=32 ,	__lowerCAmelCase				:				Optional[int]=5 ,	__lowerCAmelCase				:				Tuple=4 ,	__lowerCAmelCase				:				List[str]=4.0 ,	__lowerCAmelCase				:				Dict=2_57 ,	__lowerCAmelCase				:				Tuple=None ,	)      ->  Dict:
    _A						     =					parent
    _A						     =					is_training
    _A						     =					batch_size
    _A						     =					image_size
    _A						     =					patch_size
    _A						     =					num_channels
    _A						     =					max_token_length
    _A						     =					num_character_labels
    _A						     =					num_bpe_labels
    _A						     =					num_wordpiece_labels
    _A						     =					hidden_size
    _A						     =					num_hidden_layers
    _A						     =					num_attention_heads
    _A						     =					mlp_ratio
    _A						     =					patch_embeds_hidden_size
    _A						     =					output_hidden_states

 def 						snake_case_			(						self				:				int			)      ->  Any:
    _A						     =					floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]			)
    _A						     =					self.get_config()
    return config, pixel_values

 def 						snake_case_			(						self				:				List[Any]			)      ->  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 						snake_case_			(						self				:				Any ,	__lowerCAmelCase				:				str ,	__lowerCAmelCase				:				str			)      ->  Union[str, Any]:
    _A						     =					MgpstrForSceneTextRecognition(__lowerCAmelCase			)
    model.to(__lowerCAmelCase			)
    model.eval()
    with torch.no_grad():
       _A						     =					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				:				List[Any]			)      ->  Optional[int]:
    _A						     =					self.prepare_config_and_inputs()
    _A     ,						_A						     =					config_and_inputs
    _A						     =					{'''pixel_values''': pixel_values}
    return config, inputs_dict


@require_torch
class   lowerCamelCase__  (					_A       ,     _A       ,     unittest.TestCase):



 """simple docstring"""

 a__				:   Dict   =     (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
 a__				:   Dict   =     {"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
 a__				:   Dict   =     False

 a__				:   Optional[int]   =     False
 a__				:   str   =     False
 a__				:   List[Any]   =     False
 a__				:   Optional[Any]   =     False

 def 						snake_case_			(						self				:				Dict			)      ->  List[Any]:
    _A						     =					MgpstrModelTester(self			)
    _A						     =					ConfigTester(self ,	config_class=__lowerCAmelCase ,	has_text_modality=__lowerCAmelCase			)

 def 						snake_case_			(						self				:				Union[str, Any]			)      ->  Any:
    self.config_tester.run_common_tests()

 def 						snake_case_			(						self				:				Optional[int]			)      ->  int:
    _A						     =					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				:				Any			)      ->  List[str]:
    pass

 def 						snake_case_			(						self				:				Tuple			)      ->  Optional[Any]:
    _A     ,						_A						     =					self.model_tester.prepare_config_and_inputs_for_common()

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

 def 						snake_case_			(						self				:				Tuple			)      ->  Optional[int]:
    _A     ,						_A						     =					self.model_tester.prepare_config_and_inputs_for_common()

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

       _A						     =					['''pixel_values''']
       self.assertListEqual(arg_names[:1] ,	__lowerCAmelCase			)

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

 def 						snake_case_			(						self				:				List[str]			)      ->  Dict:
    _A     ,						_A						     =					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

       _A						     =					True
       _A						     =					model_class(__lowerCAmelCase			)
       self.assertTrue(model.is_gradient_checkpointing			)

 def 						snake_case_			(						self				:				List[str]			)      ->  str:
    def check_hidden_states_output(__lowerCAmelCase				:				int ,	__lowerCAmelCase				:				Dict ,	__lowerCAmelCase				:				Dict			):
       _A						     =					model_class(__lowerCAmelCase			)
       model.to(__lowerCAmelCase			)
       model.eval()

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

       _A						     =					outputs.hidden_states

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

    _A     ,						_A						     =					self.model_tester.prepare_config_and_inputs_for_common()

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

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

       check_hidden_states_output(__lowerCAmelCase ,	__lowerCAmelCase ,	__lowerCAmelCase			)

 def 						snake_case_			(						self				:				List[Any]			)      ->  Any:
    _A     ,						_A						     =					self.model_tester.prepare_config_and_inputs_for_common()

    _A						     =					_config_zero_init(__lowerCAmelCase			)
    for model_class in self.all_model_classes:
       _A						     =					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				:				Optional[Any]			)      ->  Dict:
    pass

def   SCREAMING_SNAKE_CASE_       (  )     ->    int:
   _A						     =					'''https://i.postimg.cc/ZKwLg2Gw/367-14.png'''
   _A						     =					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 						snake_case_			(						self				:				Union[str, Any]			)      ->  Any:
    _A						     =					'''alibaba-damo/mgp-str-base'''
    _A						     =					MgpstrForSceneTextRecognition.from_pretrained(__lowerCAmelCase			).to(__lowerCAmelCase			)
    _A						     =					MgpstrProcessor.from_pretrained(__lowerCAmelCase			)

    _A						     =					prepare_img()
    _A						     =					processor(images=__lowerCAmelCase ,	return_tensors='''pt'''			).pixel_values.to(__lowerCAmelCase			)

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

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

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

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

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

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








from __future__ import annotations

def   SCREAMING_SNAKE_CASE_       (  _snake_case  :int							)     ->    int | None:
   for r in range(1  ,      _snake_case							):
      _A						     =					[]
      for x in range(n - 1							):
         _A						     =					pow(_snake_case  ,      _snake_case  ,      _snake_case							)
         if val in li:
            break
         li.append(_snake_case							)
      else:
         return r
   return None


if __name__ == "__main__":
   UpperCAmelCase_		   =				int(input("""Enter a prime number q: """))
   UpperCAmelCase_		   =				find_primitive(q)
   if a is None:
      print(f'Cannot find the primitive for the value: {a!r}')
   else:
      UpperCAmelCase_		   =				int(input("""Enter private key of A: """))
      UpperCAmelCase_		   =				pow(a, a_private, q)
      UpperCAmelCase_		   =				int(input("""Enter private key of B: """))
      UpperCAmelCase_		   =				pow(a, b_private, q)

      UpperCAmelCase_		   =				pow(b_public, a_private, q)
      UpperCAmelCase_		   =				pow(a_public, b_private, q)

      print("""The key value generated by A is: """, a_secret)
      print("""The key value generated by B is: """, b_secret)



