



import os
import sys
import unittest


_lowercase			:			str										=						os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
_lowercase			:			List[Any]										=						os.path.join(git_repo_path, "src", "diffusers")

class 	__SCREAMING_SNAKE_CASE     (				unittest.TestCase       ):


					'''simple docstring'''





					def 		snake_case	(	self							:  List[str]					)-> Tuple:
								lowerCamelCase__		:		List[str]		     =find_backend('''    if not is_torch_available():'''					)
								self.assertEqual(UpperCamelCase__,  '''torch'''					)

								# backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
								# self.assertEqual(backend_with_underscore, "tensorflow_text")

								lowerCamelCase__		:		Optional[int]		     =find_backend('''    if not (is_torch_available() and is_transformers_available()):'''					)
								self.assertEqual(UpperCamelCase__,  '''torch_and_transformers'''					)

								# double_backend_with_underscore = find_backend(
								#    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
								# )
								# self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

								lowerCamelCase__		:		Optional[int]		     =find_backend(
								    '''    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):'''					)
								self.assertEqual(UpperCamelCase__,  '''torch_and_transformers_and_onnx'''					)



					def 		snake_case	(	self							:  int					)-> Any:
								lowerCamelCase__		:		Optional[Any]		     =read_init()
								# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
								self.assertIn('''torch''',  UpperCamelCase__					)
								self.assertIn('''torch_and_transformers''',  UpperCamelCase__					)
								self.assertIn('''flax_and_transformers''',  UpperCamelCase__					)
								self.assertIn('''torch_and_transformers_and_onnx''',  UpperCamelCase__					)

								# Likewise, we can't assert on the exact content of a key
								self.assertIn('''UNet2DModel''',  objects['''torch''']					)
								self.assertIn('''FlaxUNet2DConditionModel''',  objects['''flax''']					)
								self.assertIn('''StableDiffusionPipeline''',  objects['''torch_and_transformers''']					)
								self.assertIn('''FlaxStableDiffusionPipeline''',  objects['''flax_and_transformers''']					)
								self.assertIn('''LMSDiscreteScheduler''',  objects['''torch_and_scipy''']					)
								self.assertIn('''OnnxStableDiffusionPipeline''',  objects['''torch_and_transformers_and_onnx''']					)



					def 		snake_case	(	self							:  Any					)-> Dict:
								lowerCamelCase__		:		Dict		     =create_dummy_object('''CONSTANT''',  '''\'torch\''''					)
								self.assertEqual(UpperCamelCase__,  '''\nCONSTANT = None\n'''					)

								lowerCamelCase__		:		Optional[Any]		     =create_dummy_object('''function''',  '''\'torch\''''					)
								self.assertEqual(
								    UpperCamelCase__,  '''\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'''					)

								lowerCamelCase__		:		Optional[Any]		     ='''
class FakeClass(metaclass=DummyObject):
    _backends = \'torch\'

    def __init__(self, *args, **kwargs):
        requires_backends(self, \'torch\')

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')
'''
								lowerCamelCase__		:		int		     =create_dummy_object('''FakeClass''',  '''\'torch\''''					)
								self.assertEqual(UpperCamelCase__,  UpperCamelCase__					)




					def 		snake_case	(	self							:  Tuple					)-> List[str]:
								lowerCamelCase__		:		int		     ='''# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, ["torch"])


class FakeClass(metaclass=DummyObject):
    _backends = ["torch"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, ["torch"])

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])
'''
								lowerCamelCase__		:		Tuple		     =create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']}					)
								self.assertEqual(dummy_files['''torch'''],  UpperCamelCase__					)









"""simple docstring"""






import numpy as np
from PIL import Image






def 					snake_case__       (		__lowerCamelCase    :   np.ndarray							,		__lowerCamelCase    :   int							,		__lowerCamelCase    :   int     ):
			"""simple docstring"""
			lowerCamelCase__		:		List[Any]		     =np.array(__lowerCamelCase     )
			if arr.shape[0] != arr.shape[1]:
						raise ValueError('''The input array is not a square matrix'''     )
			lowerCamelCase__		:		int		     =0
			lowerCamelCase__		:		int		     =0
			lowerCamelCase__		:		Optional[int]		     =0
			lowerCamelCase__		:		List[Any]		     =0

			# compute the shape of the output matrix
			lowerCamelCase__		:		Union[str, Any]		     =(arr.shape[0] - size) // stride + 1
			# initialize the output matrix with zeros of shape maxpool_shape
			lowerCamelCase__		:		Union[str, Any]		     =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__		:		str		     =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__		:		Optional[int]		     =0
						lowerCamelCase__		:		Optional[int]		     =0

			return updated_arr






def 					snake_case__       (		__lowerCamelCase    :   np.ndarray							,		__lowerCamelCase    :   int							,		__lowerCamelCase    :   int     ):
			"""simple docstring"""
			lowerCamelCase__		:		List[Any]		     =np.array(__lowerCamelCase     )
			if arr.shape[0] != arr.shape[1]:
						raise ValueError('''The input array is not a square matrix'''     )
			lowerCamelCase__		:		str		     =0
			lowerCamelCase__		:		List[Any]		     =0
			lowerCamelCase__		:		Optional[int]		     =0
			lowerCamelCase__		:		List[Any]		     =0

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

			return updated_arr


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

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

		# Loading the image
		_lowercase			:			int										=						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()




