


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




						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_			:							Optional[Any]      =       floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]     )
							lowerCamelCase_			:							Dict      =       self.get_config()
							return config, pixel_values




						def 					_UpperCamelCase			(   self     ):
							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				,							a_				,							a_     ):
							lowerCamelCase_			:							Union[str, Any]      =       MgpstrForSceneTextRecognition(a_     )
							model.to(a_     )
							model.eval()
							with torch.no_grad():
								lowerCamelCase_			:							List[str]      =       model(a_     )
							self.parent.assertEqual(
							    generated_ids[0][0].shape				,							(self.batch_size, self.max_token_length, self.num_character_labels)     )




						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_			:							str      =       self.prepare_config_and_inputs()
							lowerCamelCase_   ,lowerCamelCase_			:							Optional[Any]      =       config_and_inputs
							lowerCamelCase_			:							Optional[Any]      =       {"pixel_values": pixel_values}
							return config, inputs_dict





@require_torch
class    lowerCAmelCase__				(			__lowerCamelCase,    __lowerCamelCase,    unittest.TestCase       ):






						"""simple docstring"""
						__UpperCAmelCase   :		List[str]  					=	(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
						__UpperCAmelCase   :		Union[str, Any]  					=	{'''feature-extraction''': MgpstrForSceneTextRecognition} if is_torch_available() else {}
						__UpperCAmelCase   :		Optional[Any]  					=	False

						__UpperCAmelCase   :		List[str]  					=	False
						__UpperCAmelCase   :		Union[str, Any]  					=	False
						__UpperCAmelCase   :		Optional[Any]  					=	False
						__UpperCAmelCase   :		Dict  					=	False




						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_			:							Optional[Any]      =       MgpstrModelTester(self     )
							lowerCamelCase_			:							Union[str, Any]      =       ConfigTester(self				,							config_class=a_				,							has_text_modality=a_     )




						def 					_UpperCamelCase			(   self     ):
							self.config_tester.run_common_tests()




						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_			:							Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*a_     )




						@unittest.skip(reason="MgpstrModel does not use inputs_embeds"     )
						def 					_UpperCamelCase			(   self     ):
							pass




						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_   ,lowerCamelCase_			:							List[Any]      =       self.model_tester.prepare_config_and_inputs_for_common()

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




						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_   ,lowerCamelCase_			:							Dict      =       self.model_tester.prepare_config_and_inputs_for_common()

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

								lowerCamelCase_			:							List[str]      =       ["pixel_values"]
								self.assertListEqual(arg_names[:1]				,							a_     )




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




						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_   ,lowerCamelCase_			:							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

								lowerCamelCase_			:							Union[str, Any]      =       True
								lowerCamelCase_			:							List[str]      =       model_class(a_     )
								self.assertTrue(model.is_gradient_checkpointing     )




						def 					_UpperCamelCase			(   self     ):
							def check_hidden_states_output(a_				,							a_				,							a_     ):
								lowerCamelCase_			:							Optional[int]      =       model_class(a_     )
								model.to(a_     )
								model.eval()

								with torch.no_grad():
									lowerCamelCase_			:							Optional[Any]      =       model(**self._prepare_for_class(a_				,							a_     )     )

								lowerCamelCase_			:							Union[str, Any]      =       outputs.hidden_states

								lowerCamelCase_			:							Union[str, Any]      =       getattr(
								    self.model_tester				,							"expected_num_hidden_layers"				,							self.model_tester.num_hidden_layers + 1     )
								self.assertEqual(len(a_     )				,							a_     )

								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]     )				,							[self.model_tester.patch_embeds_hidden_size, self.model_tester.hidden_size]				,							)

							lowerCamelCase_   ,lowerCamelCase_			:							str      =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								lowerCamelCase_			:							Dict      =       True
								check_hidden_states_output(a_				,							a_				,							a_     )

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								lowerCamelCase_			:							Any      =       True

								check_hidden_states_output(a_				,							a_				,							a_     )




						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_   ,lowerCamelCase_			:							List[str]      =       self.model_tester.prepare_config_and_inputs_for_common()

							lowerCamelCase_			:							Union[str, Any]      =       _config_zero_init(a_     )
							for model_class in self.all_model_classes:
								lowerCamelCase_			:							List[Any]      =       model_class(config=a_     )
								for name, param in model.named_parameters():
									if isinstance(a_				,							(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     ):
							pass







def     __magic_name__  (      ):
	'''simple docstring'''


	lowerCamelCase_			:							str      =       "https://i.postimg.cc/ZKwLg2Gw/367-14.png"
	lowerCamelCase_			:							Union[str, Any]      =       Image.open(requests.get(lowerCAmelCase_      ,					stream=lowerCAmelCase_).raw).convert("RGB")
	return im





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






						"""simple docstring"""




						@slow
						def 					_UpperCamelCase			(   self     ):
							lowerCamelCase_			:							Tuple      =       "alibaba-damo/mgp-str-base"
							lowerCamelCase_			:							Optional[Any]      =       MgpstrForSceneTextRecognition.from_pretrained(a_     ).to(a_     )
							lowerCamelCase_			:							str      =       MgpstrProcessor.from_pretrained(a_     )

							lowerCamelCase_			:							Union[str, Any]      =       prepare_img()
							lowerCamelCase_			:							Any      =       processor(images=a_				,							return_tensors="pt"     ).pixel_values.to(a_     )

							# forward pass
							with torch.no_grad():
								lowerCamelCase_			:							str      =       model(a_     )

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

							lowerCamelCase_			:							str      =       processor.batch_decode(outputs.logits     )
							lowerCamelCase_			:							Any      =       "ticket"

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

							lowerCamelCase_			:							Optional[int]      =       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=a_				,							)

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





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__magic_name__       					=      {'''configuration_detr''': ['''DETR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DetrConfig''', '''DetrOnnxConfig''']}

try:
							if not is_vision_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__magic_name__       					=      ['''DetrFeatureExtractor''']
							__magic_name__       					=      ['''DetrImageProcessor''']

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__magic_name__       					=      [
							    '''DETR_PRETRAINED_MODEL_ARCHIVE_LIST''',
							    '''DetrForObjectDetection''',
							    '''DetrForSegmentation''',
							    '''DetrModel''',
							    '''DetrPreTrainedModel''',
							]


if TYPE_CHECKING:
							from .configuration_detr import DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, DetrConfig, DetrOnnxConfig

							try:
														if not is_vision_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .feature_extraction_detr import DetrFeatureExtractor
														from .image_processing_detr import DetrImageProcessor

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_detr import (
														    DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
														    DetrForObjectDetection,
														    DetrForSegmentation,
														    DetrModel,
														    DetrPreTrainedModel,
														)

else:
							import sys

							__magic_name__       					=      _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)

