



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

					def 				__UpperCAmelCase		(		self     :Union[str, Any]    ):
										lowercase						   =       floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]    )
										lowercase						   =       self.get_config()
										return config, pixel_values

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



					def 				__UpperCAmelCase		(		self     :List[Any]    ):
										lowercase						   =       self.prepare_config_and_inputs()
										lowercase   ,      lowercase						   =       config_and_inputs
										lowercase						   =       {'pixel_values': pixel_values}
										return config, inputs_dict




@require_torch
class 	a__       (       _snake_case  ,			_snake_case  ,			unittest.TestCase       ):


					"""simple docstring"""



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

					A__  :				Optional[Any]					 =				False
					A__  :				List[Any]					 =				False
					A__  :				Union[str, Any]					 =				False
					A__  :				str					 =				False

					def 				__UpperCAmelCase		(		self     :Any    ):
										lowercase						   =       MgpstrModelTester(self    )
										lowercase						   =       ConfigTester(self      ,  config_class=lowercase__      ,  has_text_modality=lowercase__    )

					def 				__UpperCAmelCase		(		self     :int    ):
										self.config_tester.run_common_tests()

					def 				__UpperCAmelCase		(		self     :str    ):
										lowercase						   =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowercase__    )

					@unittest.skip(reason='MgpstrModel does not use inputs_embeds'    )
					def 				__UpperCAmelCase		(		self     :List[Any]    ):
										pass

					def 				__UpperCAmelCase		(		self     :Union[str, Any]    ):
										lowercase   ,      lowercase						   =       self.model_tester.prepare_config_and_inputs_for_common()

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

					def 				__UpperCAmelCase		(		self     :Optional[int]    ):
										lowercase   ,      lowercase						   =       self.model_tester.prepare_config_and_inputs_for_common()

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

															lowercase						   =       ['pixel_values']
															self.assertListEqual(arg_names[:1]      ,  lowercase__    )

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

					def 				__UpperCAmelCase		(		self     :Dict    ):
										lowercase   ,      lowercase						   =       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

															lowercase						   =       True
															lowercase						   =       model_class(lowercase__    )
															self.assertTrue(model.is_gradient_checkpointing    )

					def 				__UpperCAmelCase		(		self     :Optional[int]    ):
										def check_hidden_states_output(lowercase__     :str      ,  lowercase__     :Union[str, Any]      ,  lowercase__     :Dict    ):
															lowercase						   =       model_class(lowercase__    )
															model.to(lowercase__    )
															model.eval()

															with torch.no_grad():
																				lowercase						   =       model(**self._prepare_for_class(lowercase__      ,  lowercase__    )    )

															lowercase						   =       outputs.hidden_states

															lowercase						   =       getattr(
															    self.model_tester      ,  'expected_num_hidden_layers'      ,  self.model_tester.num_hidden_layers + 1    )
															self.assertEqual(len(lowercase__    )      ,  lowercase__    )

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

										lowercase   ,      lowercase						   =       self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
															lowercase						   =       True
															check_hidden_states_output(lowercase__      ,  lowercase__      ,  lowercase__    )

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

															check_hidden_states_output(lowercase__      ,  lowercase__      ,  lowercase__    )

					def 				__UpperCAmelCase		(		self     :Any    ):
										lowercase   ,      lowercase						   =       self.model_tester.prepare_config_and_inputs_for_common()

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





def 		__snake_case						(    ):
					"""simple docstring"""






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




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


					"""simple docstring"""



					@slow
					def 				__UpperCAmelCase		(		self     :Union[str, Any]    ):
										lowercase						   =       'alibaba-damo/mgp-str-base'
										lowercase						   =       MgpstrForSceneTextRecognition.from_pretrained(lowercase__    ).to(lowercase__    )
										lowercase						   =       MgpstrProcessor.from_pretrained(lowercase__    )

										lowercase						   =       prepare_img()
										lowercase						   =       processor(images=lowercase__      ,  return_tensors='pt'    ).pixel_values.to(lowercase__    )

										# forward pass
										with torch.no_grad():
															lowercase						   =       model(lowercase__    )

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

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

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

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

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











def 		__snake_case						(    _UpperCAmelCase       ,			_UpperCAmelCase				):
					"""simple docstring"""






					for index, item in enumerate(_UpperCAmelCase				):
										if item == target:
															return index
					return -1





def 		__snake_case						(    _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase				):
					"""simple docstring"""






					if not (0 <= high < len(_UpperCAmelCase				) and 0 <= low < len(_UpperCAmelCase				)):
										raise Exception('Invalid upper or lower bound!'				)
					if high < low:
										return -1
					if sequence[low] == target:
										return low
					if sequence[high] == target:
										return high
					return rec_linear_search(_UpperCAmelCase       ,			low + 1       ,			high - 1       ,			_UpperCAmelCase				)


if __name__ == "__main__":
		__magic_name__       =     input('''Enter numbers separated by comma:\n''').strip()
		__magic_name__       =     [int(item.strip()) for item in user_input.split(''',''')]

		__magic_name__       =     int(input('''Enter a single number to be found in the list:\n''').strip())
		__magic_name__       =     linear_search(sequence, target)
		if result != -1:
				print(F"""linear_search({sequence}, {target}) = {result}""")
		else:
				print(F"""{target} was not found in {sequence}""")






