"""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   __snake_case			:



      def __init__(		self       ,     lowercase       ,     lowercase=False       ,     lowercase=13       ,     lowercase=(32, 1_28)       ,     lowercase=4       ,     lowercase=3       ,     lowercase=27       ,     lowercase=38       ,     lowercase=99       ,     lowercase=99       ,     lowercase=32       ,     lowercase=5       ,     lowercase=4       ,     lowercase=4.0       ,     lowercase=2_57       ,     lowercase=None       ,     )      ->     int:





        '''simple docstring'''





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



      def     lowerCamelCase_  (		self)      ->     int:





        '''simple docstring'''





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



      def     lowerCamelCase_  (		self)      ->     List[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     lowerCamelCase_  (		self       ,     lowercase       ,     lowercase)      ->     List[str]:





        '''simple docstring'''





        a__:	Any     				=      MgpstrForSceneTextRecognition(lowercase)
        model.to(lowercase)
        model.eval()
        with torch.no_grad():
          a__:	List[str]     				=      model(lowercase)
        self.parent.assertEqual(
            generated_ids[0][0].shape       ,     (self.batch_size, self.max_token_length, self.num_character_labels))



      def     lowerCamelCase_  (		self)      ->     Union[str, Any]:





        '''simple docstring'''





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







@require_torch
class   __snake_case			(	__lowerCAmelCase			, __lowerCAmelCase			, unittest.TestCase							):
      a__								=						(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
      a__								=						{"""feature-extraction""": MgpstrForSceneTextRecognition} if is_torch_available() else {}
      a__								=						False

      a__								=						False
      a__								=						False
      a__								=						False
      a__								=						False



      def     lowerCamelCase_  (		self)      ->     Optional[int]:





        '''simple docstring'''





        a__:	Optional[int]     				=      MgpstrModelTester(self)
        a__:	Dict     				=      ConfigTester(self       ,     config_class=lowercase       ,     has_text_modality=lowercase)



      def     lowerCamelCase_  (		self)      ->     Union[str, Any]:





        '''simple docstring'''





        self.config_tester.run_common_tests()



      def     lowerCamelCase_  (		self)      ->     Dict:





        '''simple docstring'''





        a__:	Tuple     				=      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     lowerCamelCase_  (		self)      ->     Tuple:





        '''simple docstring'''





        pass



      def     lowerCamelCase_  (		self)      ->     Any:





        '''simple docstring'''





        a__:	int     				=      self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          a__:	Dict     				=      model_class(lowercase)
          self.assertIsInstance(model.get_input_embeddings()       ,     (nn.Module))
          a__:	Optional[Any]     				=      model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(lowercase       ,     nn.Linear))



      def     lowerCamelCase_  (		self)      ->     int:





        '''simple docstring'''





        a__:	Tuple     				=      self.model_tester.prepare_config_and_inputs_for_common()

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

          a__:	List[Any]     				=      ["""pixel_values"""]
          self.assertListEqual(arg_names[:1]       ,     lowercase)



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





        '''simple docstring'''





        pass



      def     lowerCamelCase_  (		self)      ->     List[str]:





        '''simple docstring'''





        a__:	Optional[Any]     				=      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__:	Any     				=      True
          a__:	str     				=      model_class(lowercase)
          self.assertTrue(model.is_gradient_checkpointing)



      def     lowerCamelCase_  (		self)      ->     Optional[int]:





        '''simple docstring'''





        def check_hidden_states_output(lowercase       ,     lowercase       ,     lowercase):
          a__:	List[Any]     				=      model_class(lowercase)
          model.to(lowercase)
          model.eval()

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

          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(lowercase)       ,     lowercase)

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

        a__:	Tuple     				=      self.model_tester.prepare_config_and_inputs_for_common()

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

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          a__:	str     				=      True

          check_hidden_states_output(lowercase       ,     lowercase       ,     lowercase)



      def     lowerCamelCase_  (		self)      ->     Dict:





        '''simple docstring'''





        a__:	Any     				=      self.model_tester.prepare_config_and_inputs_for_common()

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





        '''simple docstring'''





        pass







def 		__a  (      )      ->Tuple:
  a__:	str     				=      """https://i.postimg.cc/ZKwLg2Gw/367-14.png"""
  a__:	int     				=      Image.open(requests.get(_lowercase						,	stream=_lowercase  ).raw  ).convert('RGB'  )
  return im




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



      @slow
      def     lowerCamelCase_  (		self)      ->     int:





        '''simple docstring'''





        a__:	Optional[int]     				=      """alibaba-damo/mgp-str-base"""
        a__:	Dict     				=      MgpstrForSceneTextRecognition.from_pretrained(lowercase).to(lowercase)
        a__:	List[Any]     				=      MgpstrProcessor.from_pretrained(lowercase)

        a__:	Optional[int]     				=      prepare_img()
        a__:	List[Any]     				=      processor(images=lowercase       ,     return_tensors='pt').pixel_values.to(lowercase)

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

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

        a__:	str     				=      processor.batch_decode(outputs.logits)
        a__:	Tuple     				=      """ticket"""

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

        a__:	Optional[int]     				=      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=lowercase       ,     )

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







'''simple docstring'''




from __future__ import annotations

from collections.abc import Iterable

class      UpperCamelCase_					:





	def __init__(    self						,						A						,						A       )     ->     int:
								UpperCAmelCase	,	UpperCAmelCase	:						Any					=						float(A       ), float(A       )





	def __eq__(    self						,						A       )     ->     str:
								return self.x == other.x and self.y == other.y





	def __ne__(    self						,						A       )     ->     Dict:
								return not self == other





	def __gt__(    self						,						A       )     ->     Dict:
								if self.x > other.x:
															return True
								elif self.x == other.x:
															return self.y > other.y
								return False





	def __lt__(    self						,						A       )     ->     str:
								return not self > other





	def __ge__(    self						,						A       )     ->     Union[str, Any]:
								if self.x > other.x:
															return True
								elif self.x == other.x:
															return self.y >= other.y
								return False





	def __le__(    self						,						A       )     ->     List[str]:
								if self.x < other.x:
															return True
								elif self.x == other.x:
															return self.y <= other.y
								return False





	def __repr__(    self       )     ->     Tuple:
								return f'''({self.x}, {self.y})'''






	def __hash__(    self       )     ->     List[str]:
								return hash(self.x       )




def  __lowerCamelCase    (   _lowercase      ,							) ->     list[Point]:
							UpperCAmelCase	:						list[Point]					=						[]
							if list_of_tuples:
														for p in list_of_tuples:
																					if isinstance(_lowercase      ,							_lowercase						):
																												points.append(_lowercase						)
																					else:
																												try:
																																			points.append(Point(p[0]      ,							p[1]						)						)
																												except (IndexError, TypeError):
																																			print(
																																			    F'''Ignoring deformed point {p}. All points'''
																																			    """ must have at least 2 coordinates."""						)
							return points



def  __lowerCamelCase    (   _lowercase						) ->     list[Point]:

							if not hasattr(_lowercase      ,							"""__iter__"""						):
														UpperCAmelCase	:						List[str]					=						F'''Expecting an iterable object but got an non-iterable type {points}'''
														raise ValueError(_lowercase						)

							if not points:
														UpperCAmelCase	:						Optional[int]					=						F'''Expecting a list of points but got {points}'''
														raise ValueError(_lowercase						)

							return _construct_points(_lowercase						)



def  __lowerCamelCase    (   _lowercase      ,							_lowercase      ,							_lowercase						) ->     float:
							UpperCAmelCase	:						Dict					=						(a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
							return det



def  __lowerCamelCase    (   _lowercase						) ->     list[Point]:
							UpperCAmelCase	:						Optional[int]					=						sorted(_validate_input(_lowercase						)						)
							UpperCAmelCase	:						int					=						len(_lowercase						)
							UpperCAmelCase	:						Any					=						set()

							for i in range(n - 1						):
														for j in range(i + 1      ,							_lowercase						):
																					UpperCAmelCase	:						Optional[Any]					=						False
																					UpperCAmelCase	:						Optional[int]					=						True
																					for k in range(_lowercase						):
																												if k != i and k != j:
																																			UpperCAmelCase	:						Union[str, Any]					=						_det(points[i]      ,							points[j]      ,							points[k]						)

																																			if det_k > 0:
																																										UpperCAmelCase	:						Optional[int]					=						True
																																			elif det_k < 0:
																																										UpperCAmelCase	:						int					=						True
																																			else:
																																										# point[i], point[j], point[k] all lie on a straight line
																																										# if point[k] is to the left of point[i] or it's to the
																																										# right of point[j], then point[i], point[j] cannot be
																																										# part of the convex hull of A
																																										if points[k] < points[i] or points[k] > points[j]:
																																																	UpperCAmelCase	:						List[Any]					=						False
																																																	break

																												if points_left_of_ij and points_right_of_ij:
																																			UpperCAmelCase	:						Union[str, Any]					=						False
																																			break

																					if ij_part_of_convex_hull:
																												convex_set.update([points[i], points[j]]						)

							return sorted(_lowercase						)



def  __lowerCamelCase    (   _lowercase						) ->     list[Point]:
							UpperCAmelCase	:						List[str]					=						sorted(_validate_input(_lowercase						)						)
							UpperCAmelCase	:						Optional[Any]					=						len(_lowercase						)

							# divide all the points into an upper hull and a lower hull
							# the left most point and the right most point are definitely
							# members of the convex hull by definition.
							# use these two anchors to divide all the points into two hulls,
							# an upper hull and a lower hull.

							# all points to the left (above) the line joining the extreme points belong to the
							# upper hull
							# all points to the right (below) the line joining the extreme points below to the
							# lower hull
							# ignore all points on the line joining the extreme points since they cannot be
							# part of the convex hull

							UpperCAmelCase	:						List[str]					=						points[0]
							UpperCAmelCase	:						Union[str, Any]					=						points[n - 1]

							UpperCAmelCase	:						int					=						{left_most_point, right_most_point}
							UpperCAmelCase	:						Dict					=						[]
							UpperCAmelCase	:						Any					=						[]

							for i in range(1      ,							n - 1						):
														UpperCAmelCase	:						Any					=						_det(_lowercase      ,							_lowercase      ,							points[i]						)

														if det > 0:
																					upper_hull.append(points[i]						)
														elif det < 0:
																					lower_hull.append(points[i]						)

							_construct_hull(_lowercase      ,							_lowercase      ,							_lowercase      ,							_lowercase						)
							_construct_hull(_lowercase      ,							_lowercase      ,							_lowercase      ,							_lowercase						)

							return sorted(_lowercase						)



def  __lowerCamelCase    (   _lowercase      ,							_lowercase      ,							_lowercase      ,							_lowercase						) ->     None:
							if points:
														UpperCAmelCase	:						Union[str, Any]					=						None
														UpperCAmelCase	:						int					=						float("""-inf"""						)
														UpperCAmelCase	:						Tuple					=						[]

														for p in points:
																					UpperCAmelCase	:						List[Any]					=						_det(_lowercase      ,							_lowercase      ,							_lowercase						)

																					if det > 0:
																												candidate_points.append(_lowercase						)

																												if det > extreme_point_distance:
																																			UpperCAmelCase	:						List[str]					=						det
																																			UpperCAmelCase	:						Optional[Any]					=						p

														if extreme_point:
																					_construct_hull(_lowercase      ,							_lowercase      ,							_lowercase      ,							_lowercase						)
																					convex_set.add(_lowercase						)
																					_construct_hull(_lowercase      ,							_lowercase      ,							_lowercase      ,							_lowercase						)



def  __lowerCamelCase    (   _lowercase						) ->     list[Point]:
							UpperCAmelCase	:						Any					=						sorted(_validate_input(_lowercase						)						)
							UpperCAmelCase	:						Union[str, Any]					=						len(_lowercase						)

							UpperCAmelCase	:						Dict					=						points[:2]
							for i in range(2      ,							_lowercase						):
														UpperCAmelCase	:						Dict					=						_det(convex_hull[1]      ,							convex_hull[0]      ,							points[i]						)
														if det > 0:
																					convex_hull.insert(0      ,							points[i]						)
																					break
														elif det < 0:
																					convex_hull.append(points[i]						)
																					break
														else:
																					UpperCAmelCase	:						Dict					=						points[i]
							i += 1

							for j in range(_lowercase      ,							_lowercase						):
														if (
														    _det(convex_hull[0]      ,							convex_hull[-1]      ,							points[j]						) > 0
														    and _det(convex_hull[-1]      ,							convex_hull[0]      ,							points[1]						) < 0
														):
																					# The point lies within the convex hull
																					continue

														convex_hull.insert(0      ,							points[j]						)
														convex_hull.append(points[j]						)
														while _det(convex_hull[0]      ,							convex_hull[1]      ,							convex_hull[2]						) >= 0:
																					del convex_hull[1]
														while _det(convex_hull[-1]      ,							convex_hull[-2]      ,							convex_hull[-3]						) <= 0:
																					del convex_hull[-2]

    # `convex_hull` is contains the convex hull in circular order
							return sorted(convex_hull[1:] if len(_lowercase						) > 3 else convex_hull						)



def  __lowerCamelCase    (   ) ->     Tuple:
							UpperCAmelCase	:						Tuple					=						[
							    (0, 3),
							    (2, 2),
							    (1, 1),
							    (2, 1),
							    (3, 0),
							    (0, 0),
							    (3, 3),
							    (2, -1),
							    (2, -4),
							    (1, -3),
							]
							# the convex set of points is
							# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
							UpperCAmelCase	:						Tuple					=						convex_hull_bf(_lowercase						)

							UpperCAmelCase	:						List[Any]					=						convex_hull_recursive(_lowercase						)
							assert results_bf == results_recursive

							UpperCAmelCase	:						Union[str, Any]					=						convex_hull_melkman(_lowercase						)
							assert results_bf == results_melkman

							print(_lowercase						)


if __name__ == "__main__":
							main()

