






import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch


@require_torch
class     __SCREAMING_SNAKE_CASE					:






						@property
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												return self.get_dummy_input()






						@property
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												if self.block_type == "down":
																		return (4, 32, 16, 16)
												elif self.block_type == "mid":
																		return (4, 32, 32, 32)
												elif self.block_type == "up":
																		return (4, 32, 64, 64)

												raise ValueError(F"'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'."   )






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase=True     ,						_UpperCamelCase=False     ,						_UpperCamelCase=False     ,						_UpperCamelCase=False     ,						):






												"""simple docstring"""
												lowerCAmelCase__    						=						4
												lowerCAmelCase__    						=						32
												lowerCAmelCase__    						=						(32, 32)

												lowerCAmelCase__    						=						torch.manual_seed(0   )
												lowerCAmelCase__    						=						torch.device(_UpperCamelCase   )
												lowerCAmelCase__    						=						(batch_size, num_channels) + sizes
												lowerCAmelCase__    						=						randn_tensor(_UpperCamelCase     ,						generator=_UpperCamelCase     ,						device=_UpperCamelCase   )
												lowerCAmelCase__    						=						{'hidden_states': hidden_states}

												if include_temb:
																		lowerCAmelCase__    						=						1_28
																		lowerCAmelCase__    						=						randn_tensor((batch_size, temb_channels)     ,						generator=_UpperCamelCase     ,						device=_UpperCamelCase   )

												if include_res_hidden_states_tuple:
																		lowerCAmelCase__    						=						torch.manual_seed(1   )
																		lowerCAmelCase__    						=						(randn_tensor(_UpperCamelCase     ,						generator=_UpperCamelCase     ,						device=_UpperCamelCase   ),)

												if include_encoder_hidden_states:
																		lowerCAmelCase__    						=						floats_tensor((batch_size, 32, 32)   ).to(_UpperCamelCase   )

												if include_skip_sample:
																		lowerCAmelCase__    						=						randn_tensor(((batch_size, 3) + sizes)     ,						generator=_UpperCamelCase     ,						device=_UpperCamelCase   )

												return dummy_input






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						{
												    'in_channels': 32,
												    'out_channels': 32,
												    'temb_channels': 1_28,
												}
												if self.block_type == "up":
																		lowerCAmelCase__    						=						32

												if self.block_type == "mid":
																		init_dict.pop('out_channels'   )

												lowerCAmelCase__    						=						self.dummy_input
												return init_dict, inputs_dict






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.prepare_init_args_and_inputs_for_common()
												lowerCAmelCase__    						=						self.block_class(**_UpperCamelCase   )
												unet_block.to(_UpperCamelCase   )
												unet_block.eval()

												with torch.no_grad():
																		lowerCAmelCase__    						=						unet_block(**_UpperCamelCase   )

												if isinstance(_UpperCamelCase     ,						_UpperCamelCase   ):
																		lowerCAmelCase__    						=						output[0]

												self.assertEqual(output.shape     ,						self.output_shape   )

												lowerCAmelCase__    						=						output[0, -1, -3:, -3:]
												lowerCAmelCase__    						=						torch.tensor(_UpperCamelCase   ).to(_UpperCamelCase   )
												assert torch_all_close(output_slice.flatten()     ,						_UpperCamelCase     ,						atol=5E-3   )







						@unittest.skipIf(torch_device == 'mps'     ,						'Training is not supported in mps'   )
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.prepare_init_args_and_inputs_for_common()
												lowerCAmelCase__    						=						self.block_class(**_UpperCamelCase   )
												model.to(_UpperCamelCase   )
												model.train()
												lowerCAmelCase__    						=						model(**_UpperCamelCase   )

												if isinstance(_UpperCamelCase     ,						_UpperCamelCase   ):
																		lowerCAmelCase__    						=						output[0]

												lowerCAmelCase__    						=						torch.device(_UpperCamelCase   )
												lowerCAmelCase__    						=						randn_tensor(output.shape     ,						device=_UpperCamelCase   )
												lowerCAmelCase__    						=						torch.nn.functional.mse_loss(_UpperCamelCase     ,						_UpperCamelCase   )
												loss.backward()













import numpy as np
from PIL import Image







def 	_UpperCamelCase   (    UpperCamelCase_       :					np.ndarray    ,       UpperCamelCase_       :					int    ,       UpperCamelCase_       :					int		)  ->   np.ndarray:

						"""simple docstring"""



						lowerCAmelCase__    						=						np.array(UpperCamelCase_		)
						if arr.shape[0] != arr.shape[1]:
												raise ValueError('The input array is not a square matrix'		)
						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						0

						# compute the shape of the output matrix
						lowerCAmelCase__    						=						(arr.shape[0] - size) // stride + 1
						# initialize the output matrix with zeros of shape maxpool_shape
						lowerCAmelCase__    						=						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
																		lowerCAmelCase__    						=						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
												lowerCAmelCase__    						=						0
												lowerCAmelCase__    						=						0

						return updated_arr







def 	_UpperCamelCase   (    UpperCamelCase_       :					np.ndarray    ,       UpperCamelCase_       :					int    ,       UpperCamelCase_       :					int		)  ->   np.ndarray:

						"""simple docstring"""



						lowerCAmelCase__    						=						np.array(UpperCamelCase_		)
						if arr.shape[0] != arr.shape[1]:
												raise ValueError('The input array is not a square matrix'		)
						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						0

						# compute the shape of the output matrix
						lowerCAmelCase__    						=						(arr.shape[0] - size) // stride + 1
						# initialize the output matrix with zeros of shape avgpool_shape
						lowerCAmelCase__    						=						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
																		lowerCAmelCase__    						=						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
												lowerCAmelCase__    						=						0
												lowerCAmelCase__    						=						0

						return updated_arr


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

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

					# Loading the image
					__snake_case    :    List[str]         =     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()





