"""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 	__UpperCAmelCase						:







			'''simple docstring'''





			def __init__( self      ,			snake_case_      ,			snake_case_=False      ,			snake_case_=13      ,			snake_case_=(32, 128)      ,			snake_case_=4      ,			snake_case_=3      ,			snake_case_=27      ,			snake_case_=38      ,			snake_case_=99      ,			snake_case_=99      ,			snake_case_=32      ,			snake_case_=5      ,			snake_case_=4      ,			snake_case_=4.0      ,			snake_case_=257      ,			snake_case_=None      ,			):







										'''simple docstring'''


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





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


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





			def 		lowerCamelCase				( 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 		lowerCamelCase				( self      ,			snake_case_      ,			snake_case_       ):







										'''simple docstring'''


										A__					:    Optional[int]														= MgpstrForSceneTextRecognition(snake_case_       )
										model.to(snake_case_       )
										model.eval()
										with torch.no_grad():
																	A__					:    Dict														= model(snake_case_       )
										self.parent.assertEqual(
										    generated_ids[0][0].shape      ,			(self.batch_size, self.max_token_length, self.num_character_labels)       )





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__					:    List[str]														= self.prepare_config_and_inputs()
										A__							,       A__					:    Dict														= config_and_inputs
										A__					:    Dict														= {"""pixel_values""": pixel_values}
										return config, inputs_dict





@require_torch
class 	__UpperCAmelCase						(__A       ,      __A       ,      unittest.TestCase    ):







			'''simple docstring'''
			_UpperCamelCase     :	Union[str, Any]				    =							(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
			_UpperCamelCase     :	int				    =							{'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
			_UpperCamelCase     :	str				    =							False

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





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__					:    List[Any]														= MgpstrModelTester(self       )
										A__					:    int														= ConfigTester(self      ,			config_class=snake_case_      ,			has_text_modality=snake_case_       )





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										self.config_tester.run_common_tests()





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__					:    Any														= 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 		lowerCamelCase				( self       ):







										'''simple docstring'''


										pass





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__							,       A__					:    Union[str, Any]														= self.model_tester.prepare_config_and_inputs_for_common()

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





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


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

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

																	A__					:    Any														= ["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]      ,			snake_case_       )





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







										'''simple docstring'''


										pass





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__							,       A__					:    Union[str, 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

																	A__					:    Dict														= True
																	A__					:    Optional[Any]														= model_class(snake_case_       )
																	self.assertTrue(model.is_gradient_checkpointing       )





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										def check_hidden_states_output(snake_case_      ,			snake_case_      ,			snake_case_       ):
																	A__					:    List[Any]														= model_class(snake_case_       )
																	model.to(snake_case_       )
																	model.eval()

																	with torch.no_grad():
																								A__					:    Tuple														= model(**self._prepare_for_class(snake_case_      ,			snake_case_       )       )

																	A__					:    Tuple														= outputs.hidden_states

																	A__					:    List[str]														= 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]      ,			)

										A__							,       A__					:    Optional[int]														= self.model_tester.prepare_config_and_inputs_for_common()

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

																	check_hidden_states_output(snake_case_      ,			snake_case_      ,			snake_case_       )





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


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

										A__					:    Union[str, Any]														= _config_zero_init(snake_case_       )
										for model_class in self.all_model_classes:
																	A__					:    Optional[int]														= 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 		lowerCamelCase				( self       ):







										'''simple docstring'''


										pass





def    _A(		):
							A__					:    Tuple														= """https://i.postimg.cc/ZKwLg2Gw/367-14.png"""
							A__					:    Optional[int]														= Image.open(requests.get(lowerCAmelCase ,     stream=lowerCAmelCase       ).raw       ).convert("""RGB"""       )
							return im



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







			'''simple docstring'''





			@slow
			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__					:    Optional[int]														= """alibaba-damo/mgp-str-base"""
										A__					:    int														= MgpstrForSceneTextRecognition.from_pretrained(snake_case_       ).to(snake_case_       )
										A__					:    List[str]														= MgpstrProcessor.from_pretrained(snake_case_       )

										A__					:    Tuple														= prepare_img()
										A__					:    int														= processor(images=snake_case_      ,			return_tensors="""pt"""       ).pixel_values.to(snake_case_       )

										# forward pass
										with torch.no_grad():
																	A__					:    Tuple														= model(snake_case_       )

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

										A__					:    List[Any]														= processor.batch_decode(outputs.logits       )
										A__					:    Dict														= """ticket"""

										self.assertEqual(out_strs["""generated_text"""][0]      ,			snake_case_       )

										A__					:    str														= torch.tensor(
										    [[[-39.53_97, -44.40_24, -36.18_44], [-61.47_09, -63.86_39, -58.34_54], [-74.02_25, -68.54_94, -71.21_64]]]      ,			device=snake_case_      ,			)

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






"""simple docstring"""



import enum
import inspect
import warnings
from functools import wraps
from typing import Callable, Optional

from .logging import get_logger


_UpperCamelCase         =		set()
_UpperCamelCase         =		get_logger(__name__)

def    _A(		lowerCAmelCase = None       ):

							def decorator(lowerCAmelCase       ):
														global _emitted_deprecation_warnings

														if inspect.isclass(lowerCAmelCase       ):
																					A__					:    List[Any]														= deprecated_class_or_function.__init__
																					A__					:    Any														= deprecated_class_or_function.__name__
														else:
																					A__					:    Dict														= deprecated_class_or_function
																					A__					:    Optional[int]														= deprecated_function.__name__
																					# Support deprecating __init__ class method: class name instead
																					A__					:    List[str]														= name if name != """__init__""" else deprecated_function.__qualname__.split("""."""       )[-2]

														A__					:    Union[str, Any]														= (
														    F'''{name} is deprecated and will be removed in the next major version of datasets.''' + F''' {help_message}'''
														    if help_message
														    else """"""
														)

														@wraps(lowerCAmelCase       )
														def wrapper(*lowerCAmelCase ,     **lowerCAmelCase       ):
																					A__					:    Tuple														= hash(lowerCAmelCase       )
																					if func_hash not in _emitted_deprecation_warnings:
																												warnings.warn(lowerCAmelCase ,     category=lowerCAmelCase ,     stacklevel=2       )
																												_emitted_deprecation_warnings.add(lowerCAmelCase       )
																					return deprecated_function(*lowerCAmelCase ,     **lowerCAmelCase       )

														A__					:    int														= """deprecated"""

														if inspect.isclass(lowerCAmelCase       ):
																					A__					:    Union[str, Any]														= wrapper
																					return deprecated_class_or_function
														else:
																					return wrapper

							return decorator
class 	__UpperCAmelCase						(enum.EnumMeta    ):







			'''simple docstring'''





			def __getattribute__( cls      ,			snake_case_       ):







										'''simple docstring'''


										A__					:    Union[str, Any]														= super().__getattribute__(snake_case_       )
										if isinstance(snake_case_      ,			enum.Enum       ) and obj._on_access:
																	obj._on_access()
										return obj





			def __getitem__( cls      ,			snake_case_       ):







										'''simple docstring'''


										A__					:    Tuple														= super().__getitem__(snake_case_       )
										if member._on_access:
																	member._on_access()
										return member





			def __call__( cls      ,			snake_case_      ,			snake_case_=None      ,			*, snake_case_=None      ,			snake_case_=None      ,			snake_case_=None      ,			snake_case_=1       ):







										'''simple docstring'''


										A__					:    List[Any]														= super().__call__(snake_case_      ,			snake_case_      ,			module=snake_case_      ,			qualname=snake_case_      ,			type=snake_case_      ,			start=snake_case_       )
										if isinstance(snake_case_      ,			enum.Enum       ) and obj._on_access:
																	obj._on_access()
										return obj





class 	__UpperCAmelCase						(enum.Enum       ,      metaclass=__A    ):







			'''simple docstring'''





			def __new__( cls      ,			snake_case_       ):







										'''simple docstring'''


										A__					:    Tuple														= object.__new__(cls       )
										A__					:    int														= value
										A__					:    Optional[int]														= member.deprecate
										return member





			@property
			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										return ""





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__					:    Tuple														= F''' {self.help_message}''' if self.help_message else """"""
										warnings.warn(
										    F'''\'{self.__objclass__.__name__}\' is deprecated and will be removed in the next major version of datasets.'''
										    + help_message      ,			snake_case_      ,			stacklevel=3      ,			)





