
'''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       ,							__SCREAMING_SNAKE_CASE       ,							__SCREAMING_SNAKE_CASE=False       ,							__SCREAMING_SNAKE_CASE=13       ,							__SCREAMING_SNAKE_CASE=(32, 1_28)       ,							__SCREAMING_SNAKE_CASE=4       ,							__SCREAMING_SNAKE_CASE=3       ,							__SCREAMING_SNAKE_CASE=27       ,							__SCREAMING_SNAKE_CASE=38       ,							__SCREAMING_SNAKE_CASE=99       ,							__SCREAMING_SNAKE_CASE=99       ,							__SCREAMING_SNAKE_CASE=32       ,							__SCREAMING_SNAKE_CASE=5       ,							__SCREAMING_SNAKE_CASE=4       ,							__SCREAMING_SNAKE_CASE=4.0       ,							__SCREAMING_SNAKE_CASE=2_57       ,							__SCREAMING_SNAKE_CASE=None       ,							):


											"""simple docstring"""





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






					def 			_snake_case					(     self	):


											"""simple docstring"""





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






					def 			_snake_case					(     self	):


											"""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       ,							__SCREAMING_SNAKE_CASE       ,							__SCREAMING_SNAKE_CASE	):


											"""simple docstring"""





											lowercase_			:  Union[str, Any]									= MgpstrForSceneTextRecognition(__SCREAMING_SNAKE_CASE	)
											model.to(__SCREAMING_SNAKE_CASE	)
											model.eval()
											with torch.no_grad():
																	lowercase_			:  List[str]									= model(__SCREAMING_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	):


											"""simple docstring"""





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







@require_torch
class 				lowerCAmelCase__     (						lowerCamelCase_					,		lowerCamelCase_					,		unittest.TestCase  ):
					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 			_snake_case					(     self	):


											"""simple docstring"""





											lowercase_			:  Optional[Any]									= MgpstrModelTester(self	)
											lowercase_			:  Dict									= ConfigTester(self       ,							config_class=__SCREAMING_SNAKE_CASE       ,							has_text_modality=__SCREAMING_SNAKE_CASE	)






					def 			_snake_case					(     self	):


											"""simple docstring"""





											self.config_tester.run_common_tests()






					def 			_snake_case					(     self	):


											"""simple docstring"""





											lowercase_			:  Dict									= 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 			_snake_case					(     self	):


											"""simple docstring"""





											pass






					def 			_snake_case					(     self	):


											"""simple docstring"""





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

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






					def 			_snake_case					(     self	):


											"""simple docstring"""





											lowercase_		,				lowercase_			:  int									= self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowercase_			:  str									= ['''pixel_values''']
																	self.assertListEqual(arg_names[:1]       ,							__SCREAMING_SNAKE_CASE	)






					@unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''	)
					def 			_snake_case					(     self	):


											"""simple docstring"""





											pass






					def 			_snake_case					(     self	):


											"""simple docstring"""





											lowercase_		,				lowercase_			:  List[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

																	lowercase_			:  Dict									= True
																	lowercase_			:  List[str]									= model_class(__SCREAMING_SNAKE_CASE	)
																	self.assertTrue(model.is_gradient_checkpointing	)






					def 			_snake_case					(     self	):


											"""simple docstring"""





											def check_hidden_states_output(__SCREAMING_SNAKE_CASE       ,							__SCREAMING_SNAKE_CASE       ,							__SCREAMING_SNAKE_CASE	):
																	lowercase_			:  Tuple									= model_class(__SCREAMING_SNAKE_CASE	)
																	model.to(__SCREAMING_SNAKE_CASE	)
																	model.eval()

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

																	lowercase_			:  int									= outputs.hidden_states

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

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

											for model_class in self.all_model_classes:
																	lowercase_			:  Optional[Any]									= 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"]
																	lowercase_			:  Union[str, Any]									= True

																	check_hidden_states_output(__SCREAMING_SNAKE_CASE       ,							__SCREAMING_SNAKE_CASE       ,							__SCREAMING_SNAKE_CASE	)






					def 			_snake_case					(     self	):


											"""simple docstring"""





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

											lowercase_			:  Union[str, Any]									= _config_zero_init(__SCREAMING_SNAKE_CASE	)
											for model_class in self.all_model_classes:
																	lowercase_			:  List[Any]									= 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 			_snake_case					(     self	):


											"""simple docstring"""





											pass







def       snake_case_	(       ):



						"""simple docstring"""





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






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






					@slow
					def 			_snake_case					(     self	):


											"""simple docstring"""





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

											lowercase_			:  Any									= prepare_img()
											lowercase_			:  Optional[Any]									= processor(images=__SCREAMING_SNAKE_CASE       ,							return_tensors='''pt'''	).pixel_values.to(__SCREAMING_SNAKE_CASE	)

											# forward pass
											with torch.no_grad():
																	lowercase_			:  List[str]									= model(__SCREAMING_SNAKE_CASE	)

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

											lowercase_			:  List[Any]									= processor.batch_decode(outputs.logits	)
											lowercase_			:  Tuple									= '''ticket'''

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

											lowercase_			:  Optional[int]									= torch.tensor(
											    [[[-39.5_397, -44.4_024, -36.1_844], [-61.4_709, -63.8_639, -58.3_454], [-74.0_225, -68.5_494, -71.2_164]]]       ,							device=__SCREAMING_SNAKE_CASE       ,							)

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





'''simple docstring'''







import math
def       snake_case_	(       __SCREAMING_SNAKE_CASE      :				int							):



						"""simple docstring"""





						if 1 < number < 4:
												# 2 and 3 are primes
												return True
						elif number < 2 or number % 2 == 0 or number % 3 == 0:
												# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
												return False

						# All primes number are in format of 6k +/- 1
						for i in range(5   ,   int(math.sqrt(__SCREAMING_SNAKE_CASE							) + 1							)   ,   6							):
												if number % i == 0 or number % (i + 2) == 0:
																		return False
						return True
def       snake_case_	(       __SCREAMING_SNAKE_CASE      :				int = 600851475143							):



						"""simple docstring"""





						try:
												lowercase_			:  List[str]									= int(__SCREAMING_SNAKE_CASE							)
						except (TypeError, ValueError):
												raise TypeError('''Parameter n must be int or castable to int.'''							)
						if n <= 0:
												raise ValueError('''Parameter n must be greater than or equal to one.'''							)
						lowercase_			:  Tuple									= 0
						if is_prime(__SCREAMING_SNAKE_CASE							):
												return n
						while n % 2 == 0:
												n //= 2
						if is_prime(__SCREAMING_SNAKE_CASE							):
												return n
						for i in range(3   ,   int(math.sqrt(__SCREAMING_SNAKE_CASE							)							) + 1   ,   2							):
												if n % i == 0:
																		if is_prime(n // i							):
																								lowercase_			:  str									= n // i
																								break
																		elif is_prime(__SCREAMING_SNAKE_CASE							):
																								lowercase_			:  Optional[Any]									= i
						return max_number


if __name__ == "__main__":
							print(f"""{solution() = }""")



