


'''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  _lowercase   :
			def __init__(	self					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			List[str]=False					,      SCREAMING_SNAKE_CASE_					:			str=13					,      SCREAMING_SNAKE_CASE_					:			List[Any]=(32, 128)					,      SCREAMING_SNAKE_CASE_					:			Tuple=4					,      SCREAMING_SNAKE_CASE_					:			Any=3					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=27					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=38					,      SCREAMING_SNAKE_CASE_					:			int=99					,      SCREAMING_SNAKE_CASE_					:			int=99					,      SCREAMING_SNAKE_CASE_					:			str=32					,      SCREAMING_SNAKE_CASE_					:			List[Any]=5					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]=4					,      SCREAMING_SNAKE_CASE_					:			List[Any]=4.0					,      SCREAMING_SNAKE_CASE_					:			List[Any]=257					,      SCREAMING_SNAKE_CASE_					:			int=None					,      )   ->       int:
								__snake_case    			=	parent
								__snake_case    			=	is_training
								__snake_case    			=	batch_size
								__snake_case    			=	image_size
								__snake_case    			=	patch_size
								__snake_case    			=	num_channels
								__snake_case    			=	max_token_length
								__snake_case    			=	num_character_labels
								__snake_case    			=	num_bpe_labels
								__snake_case    			=	num_wordpiece_labels
								__snake_case    			=	hidden_size
								__snake_case    			=	num_hidden_layers
								__snake_case    			=	num_attention_heads
								__snake_case    			=	mlp_ratio
								__snake_case    			=	patch_embeds_hidden_size
								__snake_case    			=	output_hidden_states
			def a     (	self					:			Any			)   ->       Any:
								__snake_case    			=	floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]			)
								__snake_case    			=	self.get_config()
								return config, pixel_values
			def a     (	self					:			Optional[int]			)   ->       Tuple:
								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 a     (	self					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			List[str]					,      SCREAMING_SNAKE_CASE_					:			str			)   ->       Union[str, Any]:
								__snake_case    			=	MgpstrForSceneTextRecognition(SCREAMING_SNAKE_CASE_			)
								model.to(SCREAMING_SNAKE_CASE_			)
								model.eval()
								with torch.no_grad():
													__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 a     (	self					:			str			)   ->       Dict:
								__snake_case    			=	self.prepare_config_and_inputs()
								__snake_case			,					__snake_case    			=	config_and_inputs
								__snake_case    			=	{'pixel_values': pixel_values}
								return config, inputs_dict




@require_torch
class  _lowercase   (  __lowercase	,				__lowercase	,				unittest.TestCase       ):
			_SCREAMING_SNAKE_CASE     :     str									=  (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
			_SCREAMING_SNAKE_CASE     :     Union[str, Any]									=  {"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
			_SCREAMING_SNAKE_CASE     :     List[str]									=  False

			_SCREAMING_SNAKE_CASE     :     Any									=  False
			_SCREAMING_SNAKE_CASE     :     Optional[Any]									=  False
			_SCREAMING_SNAKE_CASE     :     int									=  False
			_SCREAMING_SNAKE_CASE     :     Optional[Any]									=  False
			def a     (	self					:			Dict			)   ->       Union[str, Any]:
								__snake_case    			=	MgpstrModelTester(self			)
								__snake_case    			=	ConfigTester(self					,      config_class=SCREAMING_SNAKE_CASE_					,      has_text_modality=SCREAMING_SNAKE_CASE_			)
			def a     (	self					:			List[str]			)   ->       List[str]:
								self.config_tester.run_common_tests()
			def a     (	self					:			Optional[int]			)   ->       List[str]:
								__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 a     (	self					:			List[Any]			)   ->       Dict:
								pass
			def a     (	self					:			Dict			)   ->       Optional[Any]:
								__snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													__snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
													self.assertIsInstance(model.get_input_embeddings()					,      (nn.Module)			)
													__snake_case    			=	model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_					,      nn.Linear			)			)
			def a     (	self					:			str			)   ->       Optional[Any]:
								__snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

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

													__snake_case    			=	['pixel_values']
													self.assertListEqual(arg_names[:1]					,      SCREAMING_SNAKE_CASE_			)
			@unittest.skip(reason='MgpstrModel does not support feedforward chunking'			)
			def a     (	self					:			Tuple			)   ->       Optional[int]:
								pass
			def a     (	self					:			Optional[int]			)   ->       List[Any]:
								__snake_case			,					__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

													__snake_case    			=	True
													__snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
													self.assertTrue(model.is_gradient_checkpointing			)
			def a     (	self					:			Optional[int]			)   ->       Optional[Any]:
								def check_hidden_states_output(SCREAMING_SNAKE_CASE_					:			Dict					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			str			):
													__snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
													model.to(SCREAMING_SNAKE_CASE_			)
													model.eval()

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

													__snake_case    			=	outputs.hidden_states

													__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]					,      )

								__snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													__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"]
													__snake_case    			=	True

													check_hidden_states_output(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)
			def a     (	self					:			Tuple			)   ->       Tuple:
								__snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

								__snake_case    			=	_config_zero_init(SCREAMING_SNAKE_CASE_			)
								for model_class in self.all_model_classes:
													__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 a     (	self					:			Union[str, Any]			)   ->       List[Any]:
								pass





def      _a		() -> Optional[Any]:






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




@require_vision
@require_torch
class  _lowercase   (  unittest.TestCase       ):
			@slow
			def a     (	self					:			Dict			)   ->       str:
								__snake_case    			=	'alibaba-damo/mgp-str-base'
								__snake_case    			=	MgpstrForSceneTextRecognition.from_pretrained(SCREAMING_SNAKE_CASE_			).to(SCREAMING_SNAKE_CASE_			)
								__snake_case    			=	MgpstrProcessor.from_pretrained(SCREAMING_SNAKE_CASE_			)

								__snake_case    			=	prepare_img()
								__snake_case    			=	processor(images=SCREAMING_SNAKE_CASE_					,      return_tensors='pt'			).pixel_values.to(SCREAMING_SNAKE_CASE_			)

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

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

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

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

								__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'''




import warnings
from collections.abc import Callable
from typing import Any

import numpy
from matplotlib import pyplot

_a      :      Optional[int]       				=      0.25 + 0.0J
_a      :      Dict       				=      -0.4 + 0.6J
_a      :      List[str]       				=      -0.1 + 0.651J
_a      :      Optional[int]       				=      -2.0
_a      :      List[str]       				=      56
_a      :      Tuple       				=      2.0
_a      :      List[str]       				=      666





def      _a		(lowercase__ :      complex       ,      lowercase__ :      numpy.ndarray	) -> numpy.ndarray:






     """simple docstring"""
     return numpy.exp(lowercase__	) + c_parameter





def      _a		(lowercase__ :      complex       ,      lowercase__ :      numpy.ndarray	) -> numpy.ndarray:






     """simple docstring"""
     return z_values * z_values + c_parameter





def      _a		(lowercase__ :      float       ,      lowercase__ :      int	) -> numpy.ndarray:






     """simple docstring"""
     __snake_case    			=	numpy.linspace(-window_size       ,      lowercase__       ,      lowercase__	)
     __snake_case    			=	x.reshape((nb_pixels, 1)	)
     __snake_case    			=	numpy.linspace(-window_size       ,      lowercase__       ,      lowercase__	)
     __snake_case    			=	y.reshape((1, nb_pixels)	)
     return x + 1.0J * y





def      _a		(lowercase__ :      Callable[[Any, numpy.ndarray], numpy.ndarray]       ,      lowercase__ :      Any       ,      lowercase__ :      int       ,      lowercase__ :      numpy.ndarray       ,      lowercase__ :      float | None = None       ,      ) -> numpy.ndarray:






     """simple docstring"""
     __snake_case    			=	z_a.astype('complex64'	)
     for _ in range(lowercase__	):
          __snake_case    			=	eval_function(lowercase__       ,      lowercase__	)
          if infinity is not None:
               numpy.nan_to_num(lowercase__       ,      copy=lowercase__       ,      nan=lowercase__	)
               __snake_case    			=	infinity
     return z_n





def      _a		(lowercase__ :      str       ,      lowercase__ :      Any       ,      lowercase__ :      float       ,      lowercase__ :      numpy.ndarray       ,      ) -> None:






     """simple docstring"""
     __snake_case    			=	(abs(lowercase__	)).transpose()
     __snake_case    			=	abs_z_final[::-1, :]
     pyplot.matshow(abs_z_final < escape_radius	)
     pyplot.title(f'Julia set of ${function_label}$, $c={function_params}$'	)
     pyplot.show()





def      _a		() -> None:






     """simple docstring"""
     warnings.filterwarnings(
         'ignore'       ,      category=lowercase__       ,      message='overflow encountered in multiply'	)
     warnings.filterwarnings(
         'ignore'       ,      category=lowercase__       ,      message='invalid value encountered in multiply'       ,      )
     warnings.filterwarnings(
         'ignore'       ,      category=lowercase__       ,      message='overflow encountered in absolute'	)
     warnings.filterwarnings(
         'ignore'       ,      category=lowercase__       ,      message='overflow encountered in exp'	)


if __name__ == "__main__":
       _a      :      List[Any]       				=      prepare_grid(window_size, nb_pixels)

       ignore_overflow_warnings()  # See file header for explanations

       _a      :      Optional[Any]       				=      24
       _a      :      Optional[int]       				=      2 * abs(c_cauliflower) + 1
       _a      :      List[str]       				=      iterate_function(
           eval_quadratic_polynomial,
           c_cauliflower,
           nb_iterations,
           z_a,
           infinity=1.1 * escape_radius,
       )
       show_results("z^2+c", c_cauliflower, escape_radius, z_final)

       _a      :      str       				=      64
       _a      :      Tuple       				=      2 * abs(c_polynomial_a) + 1
       _a      :      List[Any]       				=      iterate_function(
           eval_quadratic_polynomial,
           c_polynomial_a,
           nb_iterations,
           z_a,
           infinity=1.1 * escape_radius,
       )
       show_results("z^2+c", c_polynomial_a, escape_radius, z_final)

       _a      :      List[Any]       				=      161
       _a      :      Tuple       				=      2 * abs(c_polynomial_a) + 1
       _a      :      int       				=      iterate_function(
           eval_quadratic_polynomial,
           c_polynomial_a,
           nb_iterations,
           z_a,
           infinity=1.1 * escape_radius,
       )
       show_results("z^2+c", c_polynomial_a, escape_radius, z_final)

       _a      :      str       				=      12
       _a      :      Optional[Any]       				=      10_000.0
       _a      :      Dict       				=      iterate_function(
           eval_exponential,
           c_exponential,
           nb_iterations,
           z_a + 2,
           infinity=1.0e1_0,
       )
       show_results("e^z+c", c_exponential, escape_radius, z_final)




