
'''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 					a_					:




       def __init__(       self				,				snake_case_				,				snake_case_=False				,				snake_case_=1_3				,				snake_case_=(3_2, 1_2_8)				,				snake_case_=4				,				snake_case_=3				,				snake_case_=2_7				,				snake_case_=3_8				,				snake_case_=9_9				,				snake_case_=9_9				,				snake_case_=3_2				,				snake_case_=5				,				snake_case_=4				,				snake_case_=4.0				,				snake_case_=2_5_7				,				snake_case_=None				,				):
         _lowerCAmelCase    :					Optional[int]							=   parent
         _lowerCAmelCase    :					str							=   is_training
         _lowerCAmelCase    :					Any							=   batch_size
         _lowerCAmelCase    :					Tuple							=   image_size
         _lowerCAmelCase    :					Optional[int]							=   patch_size
         _lowerCAmelCase    :					Tuple							=   num_channels
         _lowerCAmelCase    :					str							=   max_token_length
         _lowerCAmelCase    :					Union[str, Any]							=   num_character_labels
         _lowerCAmelCase    :					int							=   num_bpe_labels
         _lowerCAmelCase    :					str							=   num_wordpiece_labels
         _lowerCAmelCase    :					List[Any]							=   hidden_size
         _lowerCAmelCase    :					str							=   num_hidden_layers
         _lowerCAmelCase    :					int							=   num_attention_heads
         _lowerCAmelCase    :					Optional[int]							=   mlp_ratio
         _lowerCAmelCase    :					Optional[int]							=   patch_embeds_hidden_size
         _lowerCAmelCase    :					Tuple							=   output_hidden_states




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Optional[Any]							=   floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]					)
         _lowerCAmelCase    :					List[Any]							=   self.get_config()
         return config, pixel_values




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







       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					int							=   self.prepare_config_and_inputs()
         _lowerCAmelCase			,   _lowerCAmelCase    :					int							=   config_and_inputs
         _lowerCAmelCase    :					List[Any]							=   {"""pixel_values""": pixel_values}
         return config, inputs_dict



@require_torch
class 					a_					(lowerCamelCase__							,     lowerCamelCase__							,     unittest.TestCase      ):
       __lowerCAmelCase      :			int      = (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
       __lowerCAmelCase      :			List[Any]      = {'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
       __lowerCAmelCase      :			List[str]      = False

       __lowerCAmelCase      :			Any      = False
       __lowerCAmelCase      :			int      = False
       __lowerCAmelCase      :			Any      = False
       __lowerCAmelCase      :			List[str]      = False




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					str							=   MgpstrModelTester(self					)
         _lowerCAmelCase    :					List[Any]							=   ConfigTester(self				,				config_class=lowercase_				,				has_text_modality=lowercase_					)




       def 							__UpperCamelCase    (       self					):
         self.config_tester.run_common_tests()




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Any							=   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					):
         pass




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase			,   _lowerCAmelCase    :					Tuple							=   self.model_tester.prepare_config_and_inputs_for_common()

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




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase			,   _lowerCAmelCase    :					int							=   self.model_tester.prepare_config_and_inputs_for_common()

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

           _lowerCAmelCase    :					Dict							=   ["""pixel_values"""]
           self.assertListEqual(arg_names[:1]				,				lowercase_					)




       @unittest.skip(reason="""MgpstrModel does not support feedforward chunking"""					)
       def 							__UpperCamelCase    (       self					):
         pass




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase			,   _lowerCAmelCase    :					str							=   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    :					List[str]							=   True
           _lowerCAmelCase    :					Any							=   model_class(lowercase_					)
           self.assertTrue(model.is_gradient_checkpointing					)




       def 							__UpperCamelCase    (       self					):






         def check_hidden_states_output(snake_case_				,				snake_case_				,				snake_case_					):
           _lowerCAmelCase    :					int							=   model_class(lowercase_					)
           model.to(lowercase_					)
           model.eval()

           with torch.no_grad():
             _lowerCAmelCase    :					Dict							=   model(**self._prepare_for_class(lowercase_				,				lowercase_					)					)

           _lowerCAmelCase    :					str							=   outputs.hidden_states

           _lowerCAmelCase    :					Any							=   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]				,				)

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

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

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           _lowerCAmelCase    :					Optional[int]							=   True

           check_hidden_states_output(lowercase_				,				lowercase_				,				lowercase_					)




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase			,   _lowerCAmelCase    :					Optional[int]							=   self.model_tester.prepare_config_and_inputs_for_common()

         _lowerCAmelCase    :					Optional[Any]							=   _config_zero_init(lowercase_					)
         for model_class in self.all_model_classes:
           _lowerCAmelCase    :					Dict							=   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					):
         pass



def 		_UpperCAmelCase			(					)      ->  List[str]:
  _lowerCAmelCase    :					Optional[Any]							=   """https://i.postimg.cc/ZKwLg2Gw/367-14.png"""
  _lowerCAmelCase    :					Dict							=   Image.open(requests.get(_A					, stream=_A						).raw						).convert("""RGB"""						)
  return im



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




       @slow
       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					int							=   """alibaba-damo/mgp-str-base"""
         _lowerCAmelCase    :					Any							=   MgpstrForSceneTextRecognition.from_pretrained(lowercase_					).to(lowercase_					)
         _lowerCAmelCase    :					Dict							=   MgpstrProcessor.from_pretrained(lowercase_					)

         _lowerCAmelCase    :					List[Any]							=   prepare_img()
         _lowerCAmelCase    :					int							=   processor(images=lowercase_				,				return_tensors="""pt"""					).pixel_values.to(lowercase_					)

         # forward pass
         with torch.no_grad():
           _lowerCAmelCase    :					List[str]							=   model(lowercase_					)

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

         _lowerCAmelCase    :					Dict							=   processor.batch_decode(outputs.logits					)
         _lowerCAmelCase    :					List[str]							=   """ticket"""

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

         _lowerCAmelCase    :					List[Any]							=   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					)					)



'''simple docstring'''

from __future__ import annotations


class 					a_					:




       def __init__(       self				,				snake_case_ = 0					):
         _lowerCAmelCase    :					Optional[Any]							=   value
         _lowerCAmelCase    :					Node | None							=   None
         _lowerCAmelCase    :					Node | None							=   None



def 		_UpperCAmelCase			(					_lowerCamelCase  :    Node | None					, _lowerCamelCase  :    Node | None						)      ->  Node | None:
  if treea is None:
    return treea
  if treea is None:
    return treea

  _lowerCAmelCase    :					Any							=   treea.value + treea.value
  _lowerCAmelCase    :					Tuple							=   merge_two_binary_trees(treea.left					, treea.left						)
  _lowerCAmelCase    :					List[str]							=   merge_two_binary_trees(treea.right					, treea.right						)
  return treea


def 		_UpperCAmelCase			(					_lowerCamelCase  :    Node | None						)      ->  None:
  if root:
    print(root.value						)
    print_preorder(root.left						)
    print_preorder(root.right						)


if __name__ == "__main__":
     UpperCamelCase_            =    Node(1)
     UpperCamelCase_            =    Node(2)
     UpperCamelCase_            =    Node(3)
     UpperCamelCase_            =    Node(4)

     UpperCamelCase_            =    Node(2)
     UpperCamelCase_            =    Node(4)
     UpperCamelCase_            =    Node(6)
     UpperCamelCase_            =    Node(9)
     UpperCamelCase_            =    Node(5)

     print("""Tree1 is: """)
     print_preorder(treea)
     print("""Tree2 is: """)
     print_preorder(treea)
     UpperCamelCase_            =    merge_two_binary_trees(treea, treea)
     print("""Merged Tree is: """)
     print_preorder(merged_tree)


