





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 os





def lowerCAmelCase__()    ->				int:







	'''simple docstring'''







	lowerCamelCase__        =		os.path.dirname(os.path.realpath(__snake_case							)							)
	lowerCamelCase__        =		os.path.join(__snake_case	,'''triangle.txt'''							)

	with open(__snake_case							) as in_file:
		lowerCamelCase__        =		[[int(__snake_case							) for i in line.split()] for line in in_file]

	while len(__snake_case							) != 1:
		lowerCamelCase__        =		triangle.pop()
		lowerCamelCase__        =		triangle[-1]
		for j in range(len(__snake_case							) - 1							):
			curr_row[j] += max(last_row[j]	,last_row[j + 1]							)
	return triangle[0][0]


if __name__ == "__main__":
			print(solution())



