





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  __A   :

			'''simple docstring'''







			def __init__(   self	,  __lowerCAmelCase	,  __lowerCAmelCase=False	,  __lowerCAmelCase=1_3	,  __lowerCAmelCase=(3_2, 1_2_8)	,  __lowerCAmelCase=4	,  __lowerCAmelCase=3	,  __lowerCAmelCase=2_7	,  __lowerCAmelCase=3_8	,  __lowerCAmelCase=9_9	,  __lowerCAmelCase=9_9	,  __lowerCAmelCase=3_2	,  __lowerCAmelCase=5	,  __lowerCAmelCase=4	,  __lowerCAmelCase=4.0	,  __lowerCAmelCase=2_5_7	,  __lowerCAmelCase=None	,  ):



				'''simple docstring'''







				lowerCamelCase__        =		parent
				lowerCamelCase__        =		is_training
				lowerCamelCase__        =		batch_size
				lowerCamelCase__        =		image_size
				lowerCamelCase__        =		patch_size
				lowerCamelCase__        =		num_channels
				lowerCamelCase__        =		max_token_length
				lowerCamelCase__        =		num_character_labels
				lowerCamelCase__        =		num_bpe_labels
				lowerCamelCase__        =		num_wordpiece_labels
				lowerCamelCase__        =		hidden_size
				lowerCamelCase__        =		num_hidden_layers
				lowerCamelCase__        =		num_attention_heads
				lowerCamelCase__        =		mlp_ratio
				lowerCamelCase__        =		patch_embeds_hidden_size
				lowerCamelCase__        =		output_hidden_states





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]							)
				lowerCamelCase__        =		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	,  __lowerCAmelCase	,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__        =		MgpstrForSceneTextRecognition(__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				with torch.no_grad():
					lowerCamelCase__        =		model(__lowerCAmelCase							)
				self.parent.assertEqual(
				    generated_ids[0][0].shape	,  (self.batch_size, self.max_token_length, self.num_character_labels)							)





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		self.prepare_config_and_inputs()
				lowerCamelCase__    ,     lowerCamelCase__        =		config_and_inputs
				lowerCamelCase__        =		{'''pixel_values''': pixel_values}
				return config, inputs_dict






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

			'''simple docstring'''







			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 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		MgpstrModelTester(self							)
				lowerCamelCase__        =		ConfigTester(self	,  config_class=__lowerCAmelCase	,  has_text_modality=__lowerCAmelCase							)





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				self.config_tester.run_common_tests()





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		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 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				pass





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__    ,     lowerCamelCase__        =		self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					lowerCamelCase__        =		model_class(__lowerCAmelCase							)
					self.assertIsInstance(model.get_input_embeddings()	,  (nn.Module)							)
					lowerCamelCase__        =		model.get_output_embeddings()
					self.assertTrue(x is None or isinstance(__lowerCAmelCase	,  nn.Linear							)							)





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__    ,     lowerCamelCase__        =		self.model_tester.prepare_config_and_inputs_for_common()

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

					lowerCamelCase__        =		['''pixel_values''']
					self.assertListEqual(arg_names[:1]	,  __lowerCAmelCase							)





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



				'''simple docstring'''







				pass





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__    ,     lowerCamelCase__        =		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__        =		True
					lowerCamelCase__        =		model_class(__lowerCAmelCase							)
					self.assertTrue(model.is_gradient_checkpointing							)





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				def check_hidden_states_output(__lowerCAmelCase	,  __lowerCAmelCase	,  __lowerCAmelCase							):
					lowerCamelCase__        =		model_class(__lowerCAmelCase							)
					model.to(__lowerCAmelCase							)
					model.eval()

					with torch.no_grad():
						lowerCamelCase__        =		model(**self._prepare_for_class(__lowerCAmelCase	,  __lowerCAmelCase							)							)

					lowerCamelCase__        =		outputs.hidden_states

					lowerCamelCase__        =		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]	,  )

				lowerCamelCase__    ,     lowerCamelCase__        =		self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					lowerCamelCase__        =		True
					check_hidden_states_output(__lowerCAmelCase	,  __lowerCAmelCase	,  __lowerCAmelCase							)

					# check that output_hidden_states also work using config
					del inputs_dict["output_hidden_states"]
					lowerCamelCase__        =		True

					check_hidden_states_output(__lowerCAmelCase	,  __lowerCAmelCase	,  __lowerCAmelCase							)





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__    ,     lowerCamelCase__        =		self.model_tester.prepare_config_and_inputs_for_common()

				lowerCamelCase__        =		_config_zero_init(__lowerCAmelCase							)
				for model_class in self.all_model_classes:
					lowerCamelCase__        =		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 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				pass





def lowerCAmelCase__()    ->				Tuple:







	'''simple docstring'''







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






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

			'''simple docstring'''







			@slow
			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		'''alibaba-damo/mgp-str-base'''
				lowerCamelCase__        =		MgpstrForSceneTextRecognition.from_pretrained(__lowerCAmelCase							).to(__lowerCAmelCase							)
				lowerCamelCase__        =		MgpstrProcessor.from_pretrained(__lowerCAmelCase							)

				lowerCamelCase__        =		prepare_img()
				lowerCamelCase__        =		processor(images=__lowerCAmelCase	,  return_tensors='''pt'''							).pixel_values.to(__lowerCAmelCase							)

				# forward pass
				with torch.no_grad():
					lowerCamelCase__        =		model(__lowerCAmelCase							)

				# verify the logits
				self.assertEqual(outputs.logits[0].shape	,  torch.Size((1, 2_7, 3_8)							)							)

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

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

				lowerCamelCase__        =		torch.tensor(
				    [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]	,  device=__lowerCAmelCase	,  )

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










import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
			import torch

if is_vision_available():
			from PIL import Image

			from transformers import ViltImageProcessor






class  __A   (   unittest.TestCase			):

			'''simple docstring'''







			def __init__(   self	,  __lowerCAmelCase	,  __lowerCAmelCase=7	,  __lowerCAmelCase=3	,  __lowerCAmelCase=1_8	,  __lowerCAmelCase=3_0	,  __lowerCAmelCase=4_0_0	,  __lowerCAmelCase=True	,  __lowerCAmelCase=None	,  __lowerCAmelCase=2	,  __lowerCAmelCase=True	,  __lowerCAmelCase=[0.5, 0.5, 0.5]	,  __lowerCAmelCase=[0.5, 0.5, 0.5]	,  ):



				'''simple docstring'''







				lowerCamelCase__        =		size if size is not None else {'''shortest_edge''': 3_0}
				lowerCamelCase__        =		parent
				lowerCamelCase__        =		batch_size
				lowerCamelCase__        =		num_channels
				lowerCamelCase__        =		image_size
				lowerCamelCase__        =		min_resolution
				lowerCamelCase__        =		max_resolution
				lowerCamelCase__        =		do_resize
				lowerCamelCase__        =		size
				lowerCamelCase__        =		size_divisor
				lowerCamelCase__        =		do_normalize
				lowerCamelCase__        =		image_mean
				lowerCamelCase__        =		image_std





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				return {
				    "image_mean": self.image_mean,
				    "image_std": self.image_std,
				    "do_normalize": self.do_normalize,
				    "do_resize": self.do_resize,
				    "size": self.size,
				    "size_divisor": self.size_divisor,
				}





			def 		__lowerCamelCase    (   self	,  __lowerCAmelCase	,  __lowerCAmelCase=False							):



				'''simple docstring'''







				if not batched:
					lowerCamelCase__        =		self.size['''shortest_edge''']
					lowerCamelCase__        =		image_inputs[0]
					if isinstance(__lowerCAmelCase	,  Image.Image							):
						lowerCamelCase__    ,     lowerCamelCase__        =		image.size
					else:
						lowerCamelCase__    ,     lowerCamelCase__        =		image.shape[1], image.shape[2]
					lowerCamelCase__        =		size / min(__lowerCAmelCase	,  __lowerCAmelCase							)
					if h < w:
						lowerCamelCase__    ,     lowerCamelCase__        =		size, scale * w
					else:
						lowerCamelCase__    ,     lowerCamelCase__        =		scale * h, size

					lowerCamelCase__        =		int((1_3_3_3 / 8_0_0) * size							)
					if max(__lowerCAmelCase	,  __lowerCAmelCase							) > max_size:
						lowerCamelCase__        =		max_size / max(__lowerCAmelCase	,  __lowerCAmelCase							)
						lowerCamelCase__        =		newh * scale
						lowerCamelCase__        =		neww * scale

					lowerCamelCase__    ,     lowerCamelCase__        =		int(newh + 0.5							), int(neww + 0.5							)
					lowerCamelCase__    ,     lowerCamelCase__        =		(
					    newh // self.size_divisor * self.size_divisor,
					    neww // self.size_divisor * self.size_divisor,
					)

				else:
					lowerCamelCase__        =		[]
					for image in image_inputs:
						lowerCamelCase__    ,     lowerCamelCase__        =		self.get_expected_values([image]							)
						expected_values.append((expected_height, expected_width)							)
					lowerCamelCase__        =		max(__lowerCAmelCase	,  key=lambda __lowerCAmelCase							: item[0]							)[0]
					lowerCamelCase__        =		max(__lowerCAmelCase	,  key=lambda __lowerCAmelCase							: item[1]							)[1]

				return expected_height, expected_width






@require_torch
@require_vision
class  __A   (   lowerCAmelCase      ,    unittest.TestCase			):

			'''simple docstring'''







			lowerCAmelCase_												=						ViltImageProcessor if is_vision_available() else None





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		ViltImageProcessingTester(self							)





			@property
			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				return self.image_processor_tester.prepare_image_processor_dict()





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		self.image_processing_class(**self.image_processor_dict							)
				self.assertTrue(hasattr(__lowerCAmelCase	,  '''image_mean'''							)							)
				self.assertTrue(hasattr(__lowerCAmelCase	,  '''image_std'''							)							)
				self.assertTrue(hasattr(__lowerCAmelCase	,  '''do_normalize'''							)							)
				self.assertTrue(hasattr(__lowerCAmelCase	,  '''do_resize'''							)							)
				self.assertTrue(hasattr(__lowerCAmelCase	,  '''size'''							)							)
				self.assertTrue(hasattr(__lowerCAmelCase	,  '''size_divisor'''							)							)





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		self.image_processing_class.from_dict(self.image_processor_dict							)
				self.assertEqual(image_processor.size	,  {'''shortest_edge''': 3_0}							)

				lowerCamelCase__        =		self.image_processing_class.from_dict(self.image_processor_dict	,  size=4_2							)
				self.assertEqual(image_processor.size	,  {'''shortest_edge''': 4_2}							)





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				pass





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		self.image_processing_class(**self.image_processor_dict							)
				# create random PIL images
				lowerCamelCase__        =		prepare_image_inputs(self.image_processor_tester	,  equal_resolution=__lowerCAmelCase							)
				for image in image_inputs:
					self.assertIsInstance(__lowerCAmelCase	,  Image.Image							)

				# Test not batched input
				lowerCamelCase__        =		image_processing(image_inputs[0]	,  return_tensors='''pt'''							).pixel_values

				lowerCamelCase__    ,     lowerCamelCase__        =		self.image_processor_tester.get_expected_values(__lowerCAmelCase							)
				self.assertEqual(
				    encoded_images.shape	,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,  )

				# Test batched
				lowerCamelCase__        =		image_processing(__lowerCAmelCase	,  return_tensors='''pt'''							).pixel_values

				lowerCamelCase__    ,     lowerCamelCase__        =		self.image_processor_tester.get_expected_values(__lowerCAmelCase	,  batched=__lowerCAmelCase							)
				self.assertEqual(
				    encoded_images.shape	,  (
				        self.image_processor_tester.batch_size,
				        self.image_processor_tester.num_channels,
				        expected_height,
				        expected_width,
				    )	,  )





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		self.image_processing_class(**self.image_processor_dict							)
				# create random numpy tensors
				lowerCamelCase__        =		prepare_image_inputs(self.image_processor_tester	,  equal_resolution=__lowerCAmelCase	,  numpify=__lowerCAmelCase							)
				for image in image_inputs:
					self.assertIsInstance(__lowerCAmelCase	,  np.ndarray							)

				# Test not batched input
				lowerCamelCase__        =		image_processing(image_inputs[0]	,  return_tensors='''pt'''							).pixel_values

				lowerCamelCase__    ,     lowerCamelCase__        =		self.image_processor_tester.get_expected_values(__lowerCAmelCase							)
				self.assertEqual(
				    encoded_images.shape	,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,  )

				# Test batched
				lowerCamelCase__        =		image_processing(__lowerCAmelCase	,  return_tensors='''pt'''							).pixel_values

				lowerCamelCase__    ,     lowerCamelCase__        =		self.image_processor_tester.get_expected_values(__lowerCAmelCase	,  batched=__lowerCAmelCase							)
				self.assertEqual(
				    encoded_images.shape	,  (
				        self.image_processor_tester.batch_size,
				        self.image_processor_tester.num_channels,
				        expected_height,
				        expected_width,
				    )	,  )





			def 		__lowerCamelCase    (   self							):



				'''simple docstring'''







				lowerCamelCase__        =		self.image_processing_class(**self.image_processor_dict							)
				# create random PyTorch tensors
				lowerCamelCase__        =		prepare_image_inputs(self.image_processor_tester	,  equal_resolution=__lowerCAmelCase	,  torchify=__lowerCAmelCase							)
				for image in image_inputs:
					self.assertIsInstance(__lowerCAmelCase	,  torch.Tensor							)

				# Test not batched input
				lowerCamelCase__        =		image_processing(image_inputs[0]	,  return_tensors='''pt'''							).pixel_values

				lowerCamelCase__    ,     lowerCamelCase__        =		self.image_processor_tester.get_expected_values(__lowerCAmelCase							)
				self.assertEqual(
				    encoded_images.shape	,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,  )

				# Test batched
				lowerCamelCase__        =		image_processing(__lowerCAmelCase	,  return_tensors='''pt'''							).pixel_values

				lowerCamelCase__    ,     lowerCamelCase__        =		self.image_processor_tester.get_expected_values(__lowerCAmelCase	,  batched=__lowerCAmelCase							)
				self.assertEqual(
				    encoded_images.shape	,  (
				        self.image_processor_tester.batch_size,
				        self.image_processor_tester.num_channels,
				        expected_height,
				        expected_width,
				    )	,  )



