






'''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       __lowercase					(unittest.TestCase    ):

	def __init__(      self   :						Tuple  ,					UpperCAmelCase_   :						Optional[int]  ,					UpperCAmelCase_   :						Optional[Any]=7  ,					UpperCAmelCase_   :						int=3  ,					UpperCAmelCase_   :						Optional[Any]=18  ,					UpperCAmelCase_   :						Union[str, Any]=30  ,					UpperCAmelCase_   :						List[str]=400  ,					UpperCAmelCase_   :						Any=None  ,					UpperCAmelCase_   :						List[str]=True  ,					UpperCAmelCase_   :						Dict=True  ,					UpperCAmelCase_   :						Tuple=None  ,					):
			UpperCamelCase__				:					Dict					=					size if size is not None else {'height': 20, 'width': 20}
			UpperCamelCase__				:					int					=					parent
			UpperCamelCase__				:					Tuple					=					batch_size
			UpperCamelCase__				:					Dict					=					num_channels
			UpperCamelCase__				:					Optional[int]					=					image_size
			UpperCamelCase__				:					Optional[int]					=					min_resolution
			UpperCamelCase__				:					Union[str, Any]					=					max_resolution
			UpperCamelCase__				:					str					=					size
			UpperCamelCase__				:					List[Any]					=					do_normalize
			UpperCamelCase__				:					Union[str, Any]					=					do_convert_rgb
			UpperCamelCase__				:					int					=					[512, 1_024, 2_048, 4_096]
			UpperCamelCase__				:					Optional[Any]					=					patch_size if patch_size is not None else {'height': 16, 'width': 16}

	def      __UpperCamelCase							(      self   :						int):
			return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}





	def      __UpperCamelCase							(      self   :						Any):
			UpperCamelCase__				:					Any					=					'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
			UpperCamelCase__				:					List[str]					=					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       __lowercase					(__lowerCamelCase   ,				unittest.TestCase    ):
	_lowerCamelCase              =  PixaStructImageProcessor if is_vision_available() else None

	def      __UpperCamelCase							(      self   :						Optional[Any]):
			UpperCamelCase__				:					str					=					PixaStructImageProcessingTester(self)

	@property
	def      __UpperCamelCase							(      self   :						Any):
			return self.image_processor_tester.prepare_image_processor_dict()

	def      __UpperCamelCase							(      self   :						Any):
			UpperCamelCase__				:					Dict					=					self.image_processing_class(**self.image_processor_dict)
			self.assertTrue(hasattr(UpperCAmelCase_  ,					'do_normalize'))
			self.assertTrue(hasattr(UpperCAmelCase_  ,					'do_convert_rgb'))

	def      __UpperCamelCase							(      self   :						int):
			UpperCamelCase__				:					Tuple					=					self.image_processor_tester.prepare_dummy_image()

			UpperCamelCase__				:					Tuple					=					self.image_processing_class(**self.image_processor_dict)
			UpperCamelCase__				:					Any					=					2_048

			UpperCamelCase__				:					List[Any]					=					image_processor(UpperCAmelCase_  ,					return_tensors='pt'  ,					max_patches=UpperCAmelCase_)
			self.assertTrue(torch.allclose(inputs.flattened_patches.mean()  ,					torch.tensor(0.06_06)  ,					atol=1e-3  ,					rtol=1e-3))

	def      __UpperCamelCase							(      self   :						Any):
			# Initialize image_processor
			UpperCamelCase__				:					List[Any]					=					self.image_processing_class(**self.image_processor_dict)
			# create random PIL images
			UpperCamelCase__				:					Any					=					prepare_image_inputs(self.image_processor_tester  ,					equal_resolution=UpperCAmelCase_)
			for image in image_inputs:
					self.assertIsInstance(UpperCAmelCase_  ,					Image.Image)

			# Test not batched input
			UpperCamelCase__				:					str					=					(
			    (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
					UpperCamelCase__				:					Optional[int]					=					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
					UpperCamelCase__				:					Any					=					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      __UpperCamelCase							(      self   :						Optional[int]):
			# Initialize image_processor
			UpperCamelCase__				:					int					=					self.image_processing_class(**self.image_processor_dict)
			# create random PIL images
			UpperCamelCase__				:					Dict					=					prepare_image_inputs(self.image_processor_tester  ,					equal_resolution=UpperCAmelCase_)
			for image in image_inputs:
					self.assertIsInstance(UpperCAmelCase_  ,					Image.Image)

			# Test not batched input
			UpperCamelCase__				:					List[Any]					=					(
			    (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
			    * self.image_processor_tester.num_channels
			) + 2

			UpperCamelCase__				:					Any					=					True

			for max_patch in self.image_processor_tester.max_patches:
					# Test not batched input
					with self.assertRaises(UpperCAmelCase_):
							UpperCamelCase__				:					Any					=					image_processor(
							    image_inputs[0]  ,					return_tensors='pt'  ,					max_patches=UpperCAmelCase_).flattened_patches

					UpperCamelCase__				:					Any					=					'Hello'

					UpperCamelCase__				:					Optional[int]					=					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
					UpperCamelCase__				:					List[str]					=					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      __UpperCamelCase							(      self   :						List[Any]):
			# Initialize image_processor
			UpperCamelCase__				:					Union[str, Any]					=					self.image_processing_class(**self.image_processor_dict)
			# create random numpy tensors
			UpperCamelCase__				:					Optional[Any]					=					prepare_image_inputs(self.image_processor_tester  ,					equal_resolution=UpperCAmelCase_  ,					numpify=UpperCAmelCase_)
			for image in image_inputs:
					self.assertIsInstance(UpperCAmelCase_  ,					np.ndarray)

			UpperCamelCase__				:					Optional[int]					=					(
			    (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
					UpperCamelCase__				:					Tuple					=					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
					UpperCamelCase__				:					Dict					=					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      __UpperCamelCase							(      self   :						Optional[int]):
			# Initialize image_processor
			UpperCamelCase__				:					Optional[Any]					=					self.image_processing_class(**self.image_processor_dict)
			# create random PyTorch tensors
			UpperCamelCase__				:					Tuple					=					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
			UpperCamelCase__				:					Optional[Any]					=					(
			    (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
					UpperCamelCase__				:					Optional[int]					=					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
					UpperCamelCase__				:					Dict					=					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       __lowercase					(__lowerCamelCase   ,				unittest.TestCase    ):
	_lowerCamelCase              =  PixaStructImageProcessor if is_vision_available() else None

	def      __UpperCamelCase							(      self   :						Union[str, Any]):
			UpperCamelCase__				:					List[Any]					=					PixaStructImageProcessingTester(self  ,					num_channels=4)
			UpperCamelCase__				:					str					=					3

	@property
	def      __UpperCamelCase							(      self   :						List[str]):
			return self.image_processor_tester.prepare_image_processor_dict()

	def      __UpperCamelCase							(      self   :						int):
			UpperCamelCase__				:					List[str]					=					self.image_processing_class(**self.image_processor_dict)
			self.assertTrue(hasattr(UpperCAmelCase_  ,					'do_normalize'))
			self.assertTrue(hasattr(UpperCAmelCase_  ,					'do_convert_rgb'))





	def      __UpperCamelCase							(      self   :						str):
			# Initialize image_processor
			UpperCamelCase__				:					Union[str, Any]					=					self.image_processing_class(**self.image_processor_dict)
			# create random PIL images
			UpperCamelCase__				:					Tuple					=					prepare_image_inputs(self.image_processor_tester  ,					equal_resolution=UpperCAmelCase_)
			for image in image_inputs:
					self.assertIsInstance(UpperCAmelCase_  ,					Image.Image)

			# Test not batched input
			UpperCamelCase__				:					Optional[Any]					=					(
			    (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
					UpperCamelCase__				:					List[Any]					=					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
					UpperCamelCase__				:					Union[str, Any]					=					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'''




import numpy as np
from PIL import Image







def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_)							->     np.ndarray:
		UpperCamelCase__				:					List[Any]					=					np.array(lowerCamelCase_)
		if arr.shape[0] != arr.shape[1]:
				raise ValueError('The input array is not a square matrix')
		UpperCamelCase__				:					Tuple					=					0
		UpperCamelCase__				:					int					=					0
		UpperCamelCase__				:					Optional[int]					=					0
		UpperCamelCase__				:					str					=					0

		# compute the shape of the output matrix
		UpperCamelCase__				:					int					=					(arr.shape[0] - size) // stride + 1
		# initialize the output matrix with zeros of shape maxpool_shape
		UpperCamelCase__				:					Dict					=					np.zeros((maxpool_shape, maxpool_shape))

		while i < arr.shape[0]:
				if i + size > arr.shape[0]:
						# if the end of the matrix is reached, break
						break
				while j < arr.shape[1]:
						# if the end of the matrix is reached, break
						if j + size > arr.shape[1]:
								break
						# compute the maximum of the pooling matrix
						UpperCamelCase__				:					Dict					=					np.max(arr[i : i + size, j : j + size])
						# shift the pooling matrix by stride of column pixels
						j += stride
						mat_j += 1

				# shift the pooling matrix by stride of row pixels
				i += stride
				mat_i += 1

				# reset the column index to 0
				UpperCamelCase__				:					List[Any]					=					0
				UpperCamelCase__				:					Optional[int]					=					0

		return updated_arr







def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_)							->     np.ndarray:
		UpperCamelCase__				:					Tuple					=					np.array(lowerCamelCase_)
		if arr.shape[0] != arr.shape[1]:
				raise ValueError('The input array is not a square matrix')
		UpperCamelCase__				:					Optional[int]					=					0
		UpperCamelCase__				:					int					=					0
		UpperCamelCase__				:					List[str]					=					0
		UpperCamelCase__				:					List[Any]					=					0

		# compute the shape of the output matrix
		UpperCamelCase__				:					str					=					(arr.shape[0] - size) // stride + 1
		# initialize the output matrix with zeros of shape avgpool_shape
		UpperCamelCase__				:					Union[str, Any]					=					np.zeros((avgpool_shape, avgpool_shape))

		while i < arr.shape[0]:
				# if the end of the matrix is reached, break
				if i + size > arr.shape[0]:
						break
				while j < arr.shape[1]:
						# if the end of the matrix is reached, break
						if j + size > arr.shape[1]:
								break
						# compute the average of the pooling matrix
						UpperCamelCase__				:					List[Any]					=					int(np.average(arr[i : i + size, j : j + size]))
						# shift the pooling matrix by stride of column pixels
						j += stride
						mat_j += 1

				# shift the pooling matrix by stride of row pixels
				i += stride
				mat_i += 1
				# reset the column index to 0
				UpperCamelCase__				:					Union[str, Any]					=					0
				UpperCamelCase__				:					Optional[Any]					=					0

		return updated_arr


# Main Function
if __name__ == "__main__":
		from doctest import testmod

		testmod(name='avgpooling', verbose=True)

		# Loading the image
		lowerCAmelCase__          =						Image.open('path_to_image')

		# Converting the image to numpy array and maxpooling, displaying the result
		# Ensure that the image is a square matrix

		Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

		# Converting the image to numpy array and averagepooling, displaying the result
		# Ensure that the image is a square matrix

		Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()




