




'''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      :       Dict							, _lowerCamelCase      :       str							, _lowerCamelCase      :       Dict=False							, _lowerCamelCase      :       List[Any]=13							, _lowerCamelCase      :       Any=(32, 128)							, _lowerCamelCase      :       List[Any]=4							, _lowerCamelCase      :       Optional[int]=3							, _lowerCamelCase      :       Tuple=27							, _lowerCamelCase      :       List[str]=38							, _lowerCamelCase      :       Optional[Any]=99							, _lowerCamelCase      :       Optional[Any]=99							, _lowerCamelCase      :       int=32							, _lowerCamelCase      :       Dict=5							, _lowerCamelCase      :       Union[str, Any]=4							, _lowerCamelCase      :       Optional[Any]=4.0							, _lowerCamelCase      :       Optional[int]=257							, _lowerCamelCase      :       Tuple=None							, ):





											"""simple docstring"""







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







						def       _a    (     self      :       List[str]    ):





											"""simple docstring"""







											A_ :     Optional[Any] =							floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]    )
											A_ :     int =							self.get_config()
											return config, pixel_values







						def       _a    (     self      :       Union[str, Any]    ):





											"""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       _a    (     self      :       Optional[Any]							, _lowerCamelCase      :       str							, _lowerCamelCase      :       List[str]    ):





											"""simple docstring"""







											A_ :     Dict =							MgpstrForSceneTextRecognition(_lowerCamelCase    )
											model.to(_lowerCamelCase    )
											model.eval()
											with torch.no_grad():
																A_ :     Optional[int] =							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[Any]    ):





											"""simple docstring"""







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






@require_torch
class     UpperCamelCase_     (a__,      a__,      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       _a    (     self      :       Optional[Any]    ):





											"""simple docstring"""







											A_ :     Union[str, Any] =							MgpstrModelTester(self    )
											A_ :     Any =							ConfigTester(self							, config_class=_lowerCamelCase							, has_text_modality=_lowerCamelCase    )







						def       _a    (     self      :       Union[str, Any]    ):





											"""simple docstring"""







											self.config_tester.run_common_tests()







						def       _a    (     self      :       Tuple    ):





											"""simple docstring"""







											A_ :     str =							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      :       Tuple    ):





											"""simple docstring"""







											pass







						def       _a    (     self      :       Any    ):





											"""simple docstring"""







											A_ ,A_ :     List[Any] =							self.model_tester.prepare_config_and_inputs_for_common()

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







						def       _a    (     self      :       Union[str, Any]    ):





											"""simple docstring"""







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

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

																A_ :     str =							['''pixel_values''']
																self.assertListEqual(arg_names[:1]							, _lowerCamelCase    )







						@unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''    )
						def       _a    (     self      :       List[Any]    ):





											"""simple docstring"""







											pass







						def       _a    (     self      :       str    ):





											"""simple docstring"""







											A_ ,A_ :     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

																A_ :     Optional[Any] =							True
																A_ :     int =							model_class(_lowerCamelCase    )
																self.assertTrue(model.is_gradient_checkpointing    )







						def       _a    (     self      :       List[str]    ):





											"""simple docstring"""







											def check_hidden_states_output(_lowerCamelCase      :       Dict							, _lowerCamelCase      :       List[Any]							, _lowerCamelCase      :       int    ):
																A_ :     Optional[Any] =							model_class(_lowerCamelCase    )
																model.to(_lowerCamelCase    )
																model.eval()

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

																A_ :     Any =							outputs.hidden_states

																A_ :     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]							, )

											A_ ,A_ :     int =							self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																A_ :     List[Any] =							True
																check_hidden_states_output(_lowerCamelCase							, _lowerCamelCase							, _lowerCamelCase    )

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

																check_hidden_states_output(_lowerCamelCase							, _lowerCamelCase							, _lowerCamelCase    )







						def       _a    (     self      :       str    ):





											"""simple docstring"""







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

											A_ :     Union[str, Any] =							_config_zero_init(_lowerCamelCase    )
											for model_class in self.all_model_classes:
																A_ :     Union[str, 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    ):





											"""simple docstring"""







											pass






def 						snake_case__    ( )   ->   Optional[Any]:
					A_ :     str =							'''https://i.postimg.cc/ZKwLg2Gw/367-14.png'''
					A_ :     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       _a    (     self      :       Optional[int]    ):





											"""simple docstring"""







											A_ :     List[str] =							'''alibaba-damo/mgp-str-base'''
											A_ :     Optional[Any] =							MgpstrForSceneTextRecognition.from_pretrained(_lowerCamelCase    ).to(_lowerCamelCase    )
											A_ :     str =							MgpstrProcessor.from_pretrained(_lowerCamelCase    )

											A_ :     Dict =							prepare_img()
											A_ :     Tuple =							processor(images=_lowerCamelCase							, return_tensors='''pt'''    ).pixel_values.to(_lowerCamelCase    )

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

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

											A_ :     Any =							processor.batch_decode(outputs.logits    )
											A_ :     Tuple =							'''ticket'''

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

											A_ :     List[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=_lowerCamelCase							, )

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









'''simple docstring'''




from __future__ import annotations

snake_case__          =						[2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]






class     UpperCamelCase_     :







						"""simple docstring"""


						def __init__(     self      :       Dict							, _lowerCamelCase      :       int    ):





											"""simple docstring"""







											A_ :     int =							-1
											A_ :     int =							-1
											A_ :     list[int] =							[-1] * length
											A_ :     Node | None =							None
											A_ :     Node | None =							None







						def __repr__(     self      :       List[str]    ):





											"""simple docstring"""







											return f'Node(min_value={self.minn} max_value={self.maxx})'






def 						snake_case__    ( lowerCamelCase__				:   list[int]			)   ->   Node | None:
					A_ :     Optional[Any] =							Node(len(lowerCamelCase__			)			)
					A_ ,A_ :     str =							min(lowerCamelCase__			), max(lowerCamelCase__			)
					# Leaf node case where the node contains only one unique value
					if root.minn == root.maxx:
										return root
					A_ :     Optional[int] =							(root.minn + root.maxx) // 2

					A_ :     list[int] =							[]
					A_ :     list[int] =							[]

					for index, num in enumerate(lowerCamelCase__			):
										if num <= pivot:
															left_arr.append(lowerCamelCase__			)
										else:
															right_arr.append(lowerCamelCase__			)
										A_ :     Union[str, Any] =							len(lowerCamelCase__			)
					A_ :     Optional[int] =							build_tree(lowerCamelCase__			)
					A_ :     Optional[int] =							build_tree(lowerCamelCase__			)
					return root




def 						snake_case__    ( lowerCamelCase__				:   Node | None			,		lowerCamelCase__				:   int			,		lowerCamelCase__				:   int			)   ->   int:
					if index < 0 or node is None:
										return 0
					# Leaf node cases
					if node.minn == node.maxx:
										return index + 1 if node.minn == num else 0
					A_ :     List[Any] =							(node.minn + node.maxx) // 2
					if num <= pivot:
										# go the left subtree and map index to the left subtree
										return rank_till_index(node.left			,		lowerCamelCase__			,		node.map_left[index] - 1			)
					else:
										# go to the right subtree and map index to the right subtree
										return rank_till_index(node.right			,		lowerCamelCase__			,		index - node.map_left[index]			)




def 						snake_case__    ( lowerCamelCase__				:   Node | None			,		lowerCamelCase__				:   int			,		lowerCamelCase__				:   int			,		lowerCamelCase__				:   int			)   ->   int:
					if start > end:
										return 0
					A_ :     Union[str, Any] =							rank_till_index(lowerCamelCase__			,		lowerCamelCase__			,		lowerCamelCase__			)
					A_ :     Union[str, Any] =							rank_till_index(lowerCamelCase__			,		lowerCamelCase__			,		start - 1			)
					return rank_till_end - rank_before_start




def 						snake_case__    ( lowerCamelCase__				:   Node | None			,		lowerCamelCase__				:   int			,		lowerCamelCase__				:   int			,		lowerCamelCase__				:   int			)   ->   int:
					if index > (end - start) or start > end or node is None:
										return -1
					# Leaf node case
					if node.minn == node.maxx:
										return node.minn
					# Number of elements in the left subtree in interval [start, end]
					A_ :     List[str] =							node.map_left[end] - (
					    node.map_left[start - 1] if start else 0
					)
					if num_elements_in_left_tree > index:
										return quantile(
										    node.left			,		lowerCamelCase__			,		(node.map_left[start - 1] if start else 0)			,		node.map_left[end] - 1			,		)
					else:
										return quantile(
										    node.right			,		index - num_elements_in_left_tree			,		start - (node.map_left[start - 1] if start else 0)			,		end - node.map_left[end]			,		)




def 						snake_case__    ( lowerCamelCase__				:   Node | None			,		lowerCamelCase__				:   int			,		lowerCamelCase__				:   int			,		lowerCamelCase__				:   int			,		lowerCamelCase__				:   int			)   ->   int:
					if (
					    start > end
					    or node is None
					    or start_num > end_num
					    or node.minn > end_num
					    or node.maxx < start_num
					):
										return 0
					if start_num <= node.minn and node.maxx <= end_num:
										return end - start + 1
					A_ :     int =							range_counting(
					    node.left			,		(node.map_left[start - 1] if start else 0)			,		node.map_left[end] - 1			,		lowerCamelCase__			,		lowerCamelCase__			,		)
					A_ :     List[str] =							range_counting(
					    node.right			,		start - (node.map_left[start - 1] if start else 0)			,		end - node.map_left[end]			,		lowerCamelCase__			,		lowerCamelCase__			,		)
					return left + right


if __name__ == "__main__":
							import doctest

							doctest.testmod()



