






'''simple docstring'''




import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

    from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
    lowerCamelCase_												=					False

if is_vision_available():
    from PIL import Image

    from transformers import PixaStructImageProcessor

class    _UpperCAmelCase			(     unittest.TestCase						):




   """simple docstring"""

   def __init__(		self :	Any      ,      __UpperCAmelCase :	Union[str, Any]      ,      __UpperCAmelCase :	Dict=7      ,      __UpperCAmelCase :	Union[str, Any]=3      ,      __UpperCAmelCase :	Dict=18      ,      __UpperCAmelCase :	str=30      ,      __UpperCAmelCase :	Dict=400      ,      __UpperCAmelCase :	Optional[Any]=None      ,      __UpperCAmelCase :	Optional[Any]=True      ,      __UpperCAmelCase :	List[Any]=True      ,      __UpperCAmelCase :	Tuple=None      ,      ):





         '''simple docstring'''





         _A			     =	size if size is not None else {"height": 20, "width": 20}
         _A			     =	parent
         _A			     =	batch_size
         _A			     =	num_channels
         _A			     =	image_size
         _A			     =	min_resolution
         _A			     =	max_resolution
         _A			     =	size
         _A			     =	do_normalize
         _A			     =	do_convert_rgb
         _A			     =	[512, 1024, 2048, 4096]
         _A			     =	patch_size if patch_size is not None else {"height": 16, "width": 16}

   def 						lowerCAmelCase (		self :	Tuple		):





         '''simple docstring'''





         return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}

   def 						lowerCAmelCase (		self :	str		):





         '''simple docstring'''





         _A			     =	"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"
         _A			     =	Image.open(requests.get(__UpperCAmelCase      ,      stream=__UpperCAmelCase		).raw		).convert("RGB"		)
         return raw_image





@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11							,    reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''							,    )
@require_torch
@require_vision
class    _UpperCAmelCase			(     snake_case_							,    unittest.TestCase						):




   """simple docstring"""

   snake_case    				=						PixaStructImageProcessor if is_vision_available() else None

   def 						lowerCAmelCase (		self :	str		):





         '''simple docstring'''





         _A			     =	PixaStructImageProcessingTester(self		)

   @property
   def 						lowerCAmelCase (		self :	Union[str, Any]		):





         '''simple docstring'''





         return self.image_processor_tester.prepare_image_processor_dict()

   def 						lowerCAmelCase (		self :	Dict		):





         '''simple docstring'''





         _A			     =	self.image_processing_class(**self.image_processor_dict		)
         self.assertTrue(hasattr(__UpperCAmelCase      ,      "do_normalize"		)		)
         self.assertTrue(hasattr(__UpperCAmelCase      ,      "do_convert_rgb"		)		)

   def 						lowerCAmelCase (		self :	Any		):





         '''simple docstring'''





         _A			     =	self.image_processor_tester.prepare_dummy_image()

         _A			     =	self.image_processing_class(**self.image_processor_dict		)
         _A			     =	2048

         _A			     =	image_processor(__UpperCAmelCase      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		)
         self.assertTrue(torch.allclose(inputs.flattened_patches.mean()      ,      torch.tensor(0.0606		)      ,      atol=1E-3      ,      rtol=1E-3		)		)

   def 						lowerCAmelCase (		self :	Any		):





         '''simple docstring'''





         _A			     =	self.image_processing_class(**self.image_processor_dict		)
         # create random PIL images
         _A			     =	prepare_image_inputs(self.image_processor_tester      ,      equal_resolution=__UpperCAmelCase		)
         for image in image_inputs:
               self.assertIsInstance(__UpperCAmelCase      ,      Image.Image		)

         # Test not batched input
         _A			     =	(
             (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
             * self.image_processor_tester.num_channels
         ) + 2

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               _A			     =	image_processor(
                   image_inputs[0]      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (1, max_patch, expected_hidden_dim)      ,      )

               # Test batched
               _A			     =	image_processor(
                   __UpperCAmelCase      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,      )

   def 						lowerCAmelCase (		self :	Dict		):





         '''simple docstring'''





         _A			     =	self.image_processing_class(**self.image_processor_dict		)
         # create random PIL images
         _A			     =	prepare_image_inputs(self.image_processor_tester      ,      equal_resolution=__UpperCAmelCase		)
         for image in image_inputs:
               self.assertIsInstance(__UpperCAmelCase      ,      Image.Image		)

         # Test not batched input
         _A			     =	(
             (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
             * self.image_processor_tester.num_channels
         ) + 2

         _A			     =	True

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               with self.assertRaises(__UpperCAmelCase		):
                     _A			     =	image_processor(
                         image_inputs[0]      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches

               _A			     =	"Hello"

               _A			     =	image_processor(
                   image_inputs[0]      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase      ,      header_text=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (1, max_patch, expected_hidden_dim)      ,      )

               # Test batched
               _A			     =	image_processor(
                   __UpperCAmelCase      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase      ,      header_text=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,      )

   def 						lowerCAmelCase (		self :	List[Any]		):





         '''simple docstring'''





         _A			     =	self.image_processing_class(**self.image_processor_dict		)
         # create random numpy tensors
         _A			     =	prepare_image_inputs(self.image_processor_tester      ,      equal_resolution=__UpperCAmelCase      ,      numpify=__UpperCAmelCase		)
         for image in image_inputs:
               self.assertIsInstance(__UpperCAmelCase      ,      np.ndarray		)

         _A			     =	(
             (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
             * self.image_processor_tester.num_channels
         ) + 2

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               _A			     =	image_processor(
                   image_inputs[0]      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (1, max_patch, expected_hidden_dim)      ,      )

               # Test batched
               _A			     =	image_processor(
                   __UpperCAmelCase      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,      )

   def 						lowerCAmelCase (		self :	List[str]		):





         '''simple docstring'''





         _A			     =	self.image_processing_class(**self.image_processor_dict		)
         # create random PyTorch tensors
         _A			     =	prepare_image_inputs(self.image_processor_tester      ,      equal_resolution=__UpperCAmelCase      ,      torchify=__UpperCAmelCase		)
         for image in image_inputs:
               self.assertIsInstance(__UpperCAmelCase      ,      torch.Tensor		)

         # Test not batched input
         _A			     =	(
             (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
             * self.image_processor_tester.num_channels
         ) + 2

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               _A			     =	image_processor(
                   image_inputs[0]      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (1, max_patch, expected_hidden_dim)      ,      )

               # Test batched
               _A			     =	image_processor(
                   __UpperCAmelCase      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,      )





@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11							,    reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''							,    )
@require_torch
@require_vision
class    _UpperCAmelCase			(     snake_case_							,    unittest.TestCase						):




   """simple docstring"""

   snake_case    				=						PixaStructImageProcessor if is_vision_available() else None

   def 						lowerCAmelCase (		self :	str		):





         '''simple docstring'''





         _A			     =	PixaStructImageProcessingTester(self      ,      num_channels=4		)
         _A			     =	3

   @property
   def 						lowerCAmelCase (		self :	str		):





         '''simple docstring'''





         return self.image_processor_tester.prepare_image_processor_dict()

   def 						lowerCAmelCase (		self :	Optional[int]		):





         '''simple docstring'''





         _A			     =	self.image_processing_class(**self.image_processor_dict		)
         self.assertTrue(hasattr(__UpperCAmelCase      ,      "do_normalize"		)		)
         self.assertTrue(hasattr(__UpperCAmelCase      ,      "do_convert_rgb"		)		)

   def 						lowerCAmelCase (		self :	str		):





         '''simple docstring'''





         _A			     =	self.image_processing_class(**self.image_processor_dict		)
         # create random PIL images
         _A			     =	prepare_image_inputs(self.image_processor_tester      ,      equal_resolution=__UpperCAmelCase		)
         for image in image_inputs:
               self.assertIsInstance(__UpperCAmelCase      ,      Image.Image		)

         # Test not batched input
         _A			     =	(
             (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
             * (self.image_processor_tester.num_channels - 1)
         ) + 2

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               _A			     =	image_processor(
                   image_inputs[0]      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (1, max_patch, expected_hidden_dim)      ,      )

               # Test batched
               _A			     =	image_processor(
                   __UpperCAmelCase      ,      return_tensors="pt"      ,      max_patches=__UpperCAmelCase		).flattened_patches
               self.assertEqual(
                   encoded_images.shape      ,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,      )






'''simple docstring'''

def 			__UpperCamelCase       (   UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase     ):

 def update_area_of_max_square(UpperCAmelCase		,     UpperCAmelCase     ) -> int:
  # BASE CASE
  if row >= rows or col >= cols:
   return 0

  lowercase__				:    int  =					update_area_of_max_square(UpperCAmelCase		,     col + 1     )
  lowercase__				:    Any  =					update_area_of_max_square(row + 1		,     col + 1     )
  lowercase__				:    str  =					update_area_of_max_square(row + 1		,     UpperCAmelCase     )

  if mat[row][col]:
   lowercase__				:    List[Any]  =					1 + min([right, diagonal, down]     )
   lowercase__				:    List[Any]  =					max(largest_square_area[0]		,     UpperCAmelCase     )
   return sub_problem_sol
  else:
   return 0

 lowercase__				:    Dict  =					[0]
 update_area_of_max_square(0		,     0     )
 return largest_square_area[0]
def 			__UpperCamelCase       (   UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase     ):

 def update_area_of_max_square_using_dp_array(
     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase     ) -> int:
  if row >= rows or col >= cols:
   return 0
  if dp_array[row][col] != -1:
   return dp_array[row][col]

  lowercase__				:    int  =					update_area_of_max_square_using_dp_array(UpperCAmelCase		,     col + 1		,     UpperCAmelCase     )
  lowercase__				:    Optional[int]  =					update_area_of_max_square_using_dp_array(row + 1		,     col + 1		,     UpperCAmelCase     )
  lowercase__				:    Any  =					update_area_of_max_square_using_dp_array(row + 1		,     UpperCAmelCase		,     UpperCAmelCase     )

  if mat[row][col]:
   lowercase__				:    Optional[int]  =					1 + min([right, diagonal, down]     )
   lowercase__				:    Any  =					max(largest_square_area[0]		,     UpperCAmelCase     )
   lowercase__				:    int  =					sub_problem_sol
   return sub_problem_sol
  else:
   return 0

 lowercase__				:    Any  =					[0]
 lowercase__				:    List[Any]  =					[[-1] * cols for _ in range(UpperCAmelCase     )]
 update_area_of_max_square_using_dp_array(0		,     0		,     UpperCAmelCase     )

 return largest_square_area[0]
def 			__UpperCamelCase       (   UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase     ):
 lowercase__				:    Optional[int]  =					[[0] * (cols + 1) for _ in range(rows + 1     )]
 lowercase__				:    str  =					0
 for row in range(rows - 1		,     -1		,     -1     ):
  for col in range(cols - 1		,     -1		,     -1     ):
   lowercase__				:    str  =					dp_array[row][col + 1]
   lowercase__				:    Optional[Any]  =					dp_array[row + 1][col + 1]
   lowercase__				:    str  =					dp_array[row + 1][col]

   if mat[row][col] == 1:
    lowercase__				:    Dict  =					1 + min(UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase     )
    lowercase__				:    str  =					max(dp_array[row][col]		,     UpperCAmelCase     )
   else:
    lowercase__				:    Any  =					0

 return largest_square_area
def 			__UpperCamelCase       (   UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase     ):
 lowercase__				:    List[str]  =					[0] * (cols + 1)
 lowercase__				:    str  =					[0] * (cols + 1)
 lowercase__				:    Tuple  =					0
 for row in range(rows - 1		,     -1		,     -1     ):
  for col in range(cols - 1		,     -1		,     -1     ):
   lowercase__				:    List[Any]  =					current_row[col + 1]
   lowercase__				:    Any  =					next_row[col + 1]
   lowercase__				:    Optional[Any]  =					next_row[col]

   if mat[row][col] == 1:
    lowercase__				:    List[str]  =					1 + min(UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase     )
    lowercase__				:    List[str]  =					max(current_row[col]		,     UpperCAmelCase     )
   else:
    lowercase__				:    int  =					0
  lowercase__				:    int  =					current_row

 return largest_square_area


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))

