
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:

						def __init__(					self		:			Any	,						_lowerCamelCase		:			Dict	,						_lowerCamelCase		:			Dict=False	,						_lowerCamelCase		:			Union[str, Any]=13	,						_lowerCamelCase		:			Optional[int]=(32, 1_28)	,						_lowerCamelCase		:			Optional[int]=4	,						_lowerCamelCase		:			int=3	,						_lowerCamelCase		:			Dict=27	,						_lowerCamelCase		:			Dict=38	,						_lowerCamelCase		:			List[str]=99	,						_lowerCamelCase		:			Tuple=99	,						_lowerCamelCase		:			Union[str, Any]=32	,						_lowerCamelCase		:			Tuple=5	,						_lowerCamelCase		:			List[Any]=4	,						_lowerCamelCase		:			List[str]=4.0	,						_lowerCamelCase		:			Union[str, Any]=2_57	,						_lowerCamelCase		:			Union[str, Any]=None	,						):
													_UpperCAmelCase  :			Union[str, Any]	       =		parent
													_UpperCAmelCase  :			List[Any]	       =		is_training
													_UpperCAmelCase  :			Dict	       =		batch_size
													_UpperCAmelCase  :			List[str]	       =		image_size
													_UpperCAmelCase  :			Any	       =		patch_size
													_UpperCAmelCase  :			Dict	       =		num_channels
													_UpperCAmelCase  :			Tuple	       =		max_token_length
													_UpperCAmelCase  :			Union[str, Any]	       =		num_character_labels
													_UpperCAmelCase  :			str	       =		num_bpe_labels
													_UpperCAmelCase  :			Optional[Any]	       =		num_wordpiece_labels
													_UpperCAmelCase  :			List[str]	       =		hidden_size
													_UpperCAmelCase  :			List[str]	       =		num_hidden_layers
													_UpperCAmelCase  :			str	       =		num_attention_heads
													_UpperCAmelCase  :			List[str]	       =		mlp_ratio
													_UpperCAmelCase  :			str	       =		patch_embeds_hidden_size
													_UpperCAmelCase  :			Any	       =		output_hidden_states

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

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






						def 						a__ (					self		:			Optional[int]			):
													_UpperCAmelCase  :			List[str]	       =		self.prepare_config_and_inputs()
													_UpperCAmelCase       ,_UpperCAmelCase  :			Optional[Any]	       =		config_and_inputs
													_UpperCAmelCase  :			Union[str, Any]	       =		{"pixel_values": pixel_values}
													return config, inputs_dict







@require_torch
class    _UpperCamelCase(   SCREAMING_SNAKE_CASE		,						SCREAMING_SNAKE_CASE		,						unittest.TestCase				):
						__A:						Any				   =      (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
						__A:						List[str]				   =      {"""feature-extraction""": MgpstrForSceneTextRecognition} if is_torch_available() else {}
						__A:						str				   =      False

						__A:						Tuple				   =      False
						__A:						Optional[Any]				   =      False
						__A:						List[Any]				   =      False
						__A:						List[Any]				   =      False

						def 						a__ (					self		:			List[Any]			):
													_UpperCAmelCase  :			Optional[Any]	       =		MgpstrModelTester(self			)
													_UpperCAmelCase  :			int	       =		ConfigTester(self	,						config_class=_lowerCamelCase	,						has_text_modality=_lowerCamelCase			)

						def 						a__ (					self		:			List[str]			):
													self.config_tester.run_common_tests()

						def 						a__ (					self		:			Optional[Any]			):
													_UpperCAmelCase  :			Tuple	       =		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 						a__ (					self		:			List[Any]			):
													pass

						def 						a__ (					self		:			Optional[Any]			):
													_UpperCAmelCase       ,_UpperCAmelCase  :			Dict	       =		self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				_UpperCAmelCase  :			List[Any]	       =		model_class(_lowerCamelCase			)
																				self.assertIsInstance(model.get_input_embeddings()	,						(nn.Module)			)
																				_UpperCAmelCase  :			Tuple	       =		model.get_output_embeddings()
																				self.assertTrue(x is None or isinstance(_lowerCamelCase	,						nn.Linear			)			)

						def 						a__ (					self		:			List[Any]			):
													_UpperCAmelCase       ,_UpperCAmelCase  :			List[Any]	       =		self.model_tester.prepare_config_and_inputs_for_common()

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

																				_UpperCAmelCase  :			List[Any]	       =		["pixel_values"]
																				self.assertListEqual(arg_names[:1]	,						_lowerCamelCase			)

						@unittest.skip(reason="MgpstrModel does not support feedforward chunking"			)
						def 						a__ (					self		:			Optional[int]			):
													pass

						def 						a__ (					self		:			Tuple			):
													_UpperCAmelCase       ,_UpperCAmelCase  :			Dict	       =		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

																				_UpperCAmelCase  :			int	       =		True
																				_UpperCAmelCase  :			Tuple	       =		model_class(_lowerCamelCase			)
																				self.assertTrue(model.is_gradient_checkpointing			)

						def 						a__ (					self		:			str			):
													def check_hidden_states_output(_lowerCamelCase		:			Optional[Any]	,						_lowerCamelCase		:			Dict	,						_lowerCamelCase		:			List[str]			):
																				_UpperCAmelCase  :			Optional[Any]	       =		model_class(_lowerCamelCase			)
																				model.to(_lowerCamelCase			)
																				model.eval()

																				with torch.no_grad():
																											_UpperCAmelCase  :			List[str]	       =		model(**self._prepare_for_class(_lowerCamelCase	,						_lowerCamelCase			)			)

																				_UpperCAmelCase  :			List[str]	       =		outputs.hidden_states

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

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

													for model_class in self.all_model_classes:
																				_UpperCAmelCase  :			str	       =		True
																				check_hidden_states_output(_lowerCamelCase	,						_lowerCamelCase	,						_lowerCamelCase			)

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

																				check_hidden_states_output(_lowerCamelCase	,						_lowerCamelCase	,						_lowerCamelCase			)

						def 						a__ (					self		:			int			):
													_UpperCAmelCase       ,_UpperCAmelCase  :			Dict	       =		self.model_tester.prepare_config_and_inputs_for_common()

													_UpperCAmelCase  :			List[Any]	       =		_config_zero_init(_lowerCamelCase			)
													for model_class in self.all_model_classes:
																				_UpperCAmelCase  :			Optional[Any]	       =		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 						a__ (					self		:			int			):
													pass







def 		lowerCAmelCase_     (     )   ->      Any:

							"""simple docstring"""






							_UpperCAmelCase  :			Dict	       =		"https://i.postimg.cc/ZKwLg2Gw/367-14.png"
							_UpperCAmelCase  :			int	       =		Image.open(requests.get(_SCREAMING_SNAKE_CASE      ,	stream=_SCREAMING_SNAKE_CASE  ).raw  ).convert("RGB"  )
							return im


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

						@slow
						def 						a__ (					self		:			Tuple			):
													_UpperCAmelCase  :			List[Any]	       =		"alibaba-damo/mgp-str-base"
													_UpperCAmelCase  :			Optional[Any]	       =		MgpstrForSceneTextRecognition.from_pretrained(_lowerCamelCase			).to(_lowerCamelCase			)
													_UpperCAmelCase  :			str	       =		MgpstrProcessor.from_pretrained(_lowerCamelCase			)

													_UpperCAmelCase  :			str	       =		prepare_img()
													_UpperCAmelCase  :			int	       =		processor(images=_lowerCamelCase	,						return_tensors="pt"			).pixel_values.to(_lowerCamelCase			)

													# forward pass
													with torch.no_grad():
																				_UpperCAmelCase  :			List[Any]	       =		model(_lowerCamelCase			)

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

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

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

													_UpperCAmelCase  :			List[Any]	       =		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=_lowerCamelCase	,						)

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






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
				import PIL


__lowerCamelCase								=					logging.get_logger(__name__)
class    _UpperCamelCase(   SCREAMING_SNAKE_CASE				):
						__A:						Union[str, Any]				   =      ["""pixel_values"""]

						def __init__(					self		:			str	,						_lowerCamelCase		:			bool = True	,						_lowerCamelCase		:			Dict[str, int] = None	,						_lowerCamelCase		:			PILImageResampling = PIL.Image.NEAREST	,						_lowerCamelCase		:			bool = False	,						_lowerCamelCase		:			Dict[str, int] = None	,						_lowerCamelCase		:			Union[int, float] = 1 / 2_55	,						_lowerCamelCase		:			bool = False	,						_lowerCamelCase		:			bool = True	,						_lowerCamelCase		:			bool = True	,						_lowerCamelCase		:			Optional[Union[float, List[float]]] = None	,						_lowerCamelCase		:			Optional[Union[float, List[float]]] = None	,						_lowerCamelCase		:			bool = True	,						**_lowerCamelCase		:			Tuple	,						):
													super().__init__(**_lowerCamelCase			)
													_UpperCAmelCase  :			int	       =		size if size is not None else {"height": 3_46, "width": 3_46}
													_UpperCAmelCase  :			Dict	       =		get_size_dict(_lowerCamelCase			)
													_UpperCAmelCase  :			List[str]	       =		crop_size if crop_size is not None else {"height": 2_89, "width": 2_89}
													_UpperCAmelCase  :			int	       =		get_size_dict(_lowerCamelCase	,						param_name="crop_size"			)

													_UpperCAmelCase  :			Dict	       =		do_resize
													_UpperCAmelCase  :			Tuple	       =		size
													_UpperCAmelCase  :			Union[str, Any]	       =		resample
													_UpperCAmelCase  :			List[Any]	       =		do_center_crop
													_UpperCAmelCase  :			List[str]	       =		crop_size
													_UpperCAmelCase  :			int	       =		do_rescale
													_UpperCAmelCase  :			str	       =		rescale_factor
													_UpperCAmelCase  :			int	       =		rescale_offset
													_UpperCAmelCase  :			Any	       =		do_normalize
													_UpperCAmelCase  :			Optional[int]	       =		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
													_UpperCAmelCase  :			List[str]	       =		image_std if image_std is not None else IMAGENET_STANDARD_STD
													_UpperCAmelCase  :			Dict	       =		include_top

						def 						a__ (					self		:			Optional[Any]	,						_lowerCamelCase		:			np.ndarray	,						_lowerCamelCase		:			Dict[str, int]	,						_lowerCamelCase		:			PILImageResampling = PIL.Image.NEAREST	,						_lowerCamelCase		:			Optional[Union[str, ChannelDimension]] = None	,						**_lowerCamelCase		:			Tuple	,						):
													_UpperCAmelCase  :			Optional[int]	       =		get_size_dict(_lowerCamelCase			)
													if "height" not in size or "width" not in size:
																				raise ValueError(f"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"""			)
													return resize(
													    _lowerCamelCase	,						size=(size["height"], size["width"])	,						resample=_lowerCamelCase	,						data_format=_lowerCamelCase	,						**_lowerCamelCase			)

						def 						a__ (					self		:			Optional[Any]	,						_lowerCamelCase		:			np.ndarray	,						_lowerCamelCase		:			Dict[str, int]	,						_lowerCamelCase		:			Optional[Union[str, ChannelDimension]] = None	,						**_lowerCamelCase		:			List[str]	,						):
													_UpperCAmelCase  :			Optional[Any]	       =		get_size_dict(_lowerCamelCase			)
													if "height" not in size or "width" not in size:
																				raise ValueError(f"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"""			)
													return center_crop(_lowerCamelCase	,						size=(size["height"], size["width"])	,						data_format=_lowerCamelCase	,						**_lowerCamelCase			)

						def 						a__ (					self		:			Optional[Any]	,						_lowerCamelCase		:			np.ndarray	,						_lowerCamelCase		:			Union[int, float]	,						_lowerCamelCase		:			bool = True	,						_lowerCamelCase		:			Optional[Union[str, ChannelDimension]] = None	,						**_lowerCamelCase		:			Tuple	,						):
													if offset:
																				_UpperCAmelCase  :			Any	       =		(image - 1_27.5) * scale
																				if data_format is not None:
																											_UpperCAmelCase  :			Union[str, Any]	       =		to_channel_dimension_format(_lowerCamelCase	,						_lowerCamelCase			)
																				_UpperCAmelCase  :			Optional[Any]	       =		rescaled_image.astype(np.floataa			)
													else:
																				_UpperCAmelCase  :			List[Any]	       =		rescale(_lowerCamelCase	,						scale=_lowerCamelCase	,						data_format=_lowerCamelCase	,						**_lowerCamelCase			)
													return rescaled_image

						def 						a__ (					self		:			Union[str, Any]	,						_lowerCamelCase		:			np.ndarray	,						_lowerCamelCase		:			Union[float, List[float]]	,						_lowerCamelCase		:			Union[float, List[float]]	,						_lowerCamelCase		:			Optional[Union[str, ChannelDimension]] = None	,						**_lowerCamelCase		:			Union[str, Any]	,						):
													return normalize(_lowerCamelCase	,						mean=_lowerCamelCase	,						std=_lowerCamelCase	,						data_format=_lowerCamelCase	,						**_lowerCamelCase			)






						def 						a__ (					self		:			str	,						_lowerCamelCase		:			ImageInput	,						_lowerCamelCase		:			bool = None	,						_lowerCamelCase		:			Dict[str, int] = None	,						_lowerCamelCase		:			List[Any]=None	,						_lowerCamelCase		:			bool = None	,						_lowerCamelCase		:			Dict[str, int] = None	,						_lowerCamelCase		:			bool = None	,						_lowerCamelCase		:			float = None	,						_lowerCamelCase		:			bool = None	,						_lowerCamelCase		:			bool = None	,						_lowerCamelCase		:			Optional[Union[float, List[float]]] = None	,						_lowerCamelCase		:			Optional[Union[float, List[float]]] = None	,						_lowerCamelCase		:			bool = None	,						_lowerCamelCase		:			Optional[Union[str, TensorType]] = None	,						_lowerCamelCase		:			ChannelDimension = ChannelDimension.FIRST	,						**_lowerCamelCase		:			str	,						):
													_UpperCAmelCase  :			Optional[Any]	       =		do_resize if do_resize is not None else self.do_resize
													_UpperCAmelCase  :			Optional[int]	       =		resample if resample is not None else self.resample
													_UpperCAmelCase  :			Tuple	       =		do_center_crop if do_center_crop is not None else self.do_center_crop
													_UpperCAmelCase  :			str	       =		do_rescale if do_rescale is not None else self.do_rescale
													_UpperCAmelCase  :			str	       =		rescale_factor if rescale_factor is not None else self.rescale_factor
													_UpperCAmelCase  :			Tuple	       =		rescale_offset if rescale_offset is not None else self.rescale_offset
													_UpperCAmelCase  :			str	       =		do_normalize if do_normalize is not None else self.do_normalize
													_UpperCAmelCase  :			Dict	       =		image_mean if image_mean is not None else self.image_mean
													_UpperCAmelCase  :			Tuple	       =		image_std if image_std is not None else self.image_std
													_UpperCAmelCase  :			Tuple	       =		include_top if include_top is not None else self.include_top

													_UpperCAmelCase  :			Optional[int]	       =		size if size is not None else self.size
													_UpperCAmelCase  :			Union[str, Any]	       =		get_size_dict(_lowerCamelCase			)
													_UpperCAmelCase  :			int	       =		crop_size if crop_size is not None else self.crop_size
													_UpperCAmelCase  :			int	       =		get_size_dict(_lowerCamelCase	,						param_name="crop_size"			)

													_UpperCAmelCase  :			Union[str, Any]	       =		make_list_of_images(_lowerCamelCase			)

													if not valid_images(_lowerCamelCase			):
																				raise ValueError(
																				    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
																				    "torch.Tensor, tf.Tensor or jax.ndarray."			)

													if do_resize and size is None or resample is None:
																				raise ValueError("Size and resample must be specified if do_resize is True."			)

													if do_center_crop and crop_size is None:
																				raise ValueError("Crop size must be specified if do_center_crop is True."			)

													if do_rescale and rescale_factor is None:
																				raise ValueError("Rescale factor must be specified if do_rescale is True."			)

													if do_normalize and (image_mean is None or image_std is None):
																				raise ValueError("Image mean and std must be specified if do_normalize is True."			)

													# All transformations expect numpy arrays.
													_UpperCAmelCase  :			Dict	       =		[to_numpy_array(_lowerCamelCase			) for image in images]

													if do_resize:
																				_UpperCAmelCase  :			Any	       =		[self.resize(image=_lowerCamelCase	,						size=_lowerCamelCase	,						resample=_lowerCamelCase			) for image in images]

													if do_center_crop:
																				_UpperCAmelCase  :			int	       =		[self.center_crop(image=_lowerCamelCase	,						size=_lowerCamelCase			) for image in images]

													if do_rescale:
																				_UpperCAmelCase  :			int	       =		[self.rescale(image=_lowerCamelCase	,						scale=_lowerCamelCase	,						offset=_lowerCamelCase			) for image in images]

													if do_normalize:
																				_UpperCAmelCase  :			str	       =		[self.normalize(image=_lowerCamelCase	,						mean=_lowerCamelCase	,						std=_lowerCamelCase			) for image in images]

													if include_top:
																				_UpperCAmelCase  :			int	       =		[self.normalize(image=_lowerCamelCase	,						mean=[0, 0, 0]	,						std=_lowerCamelCase			) for image in images]

													_UpperCAmelCase  :			str	       =		[to_channel_dimension_format(_lowerCamelCase	,						_lowerCamelCase			) for image in images]

													_UpperCAmelCase  :			Dict	       =		{"pixel_values": images}
													return BatchFeature(data=_lowerCamelCase	,						tensor_type=_lowerCamelCase			)




