





import numpy as np
from PIL import Image




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

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

       return updated_arr




def    __UpperCAmelCase(      lowercase_ ,    lowercase_ ,    lowercase_      ):
       _lowerCamelCase							:     Union[str, Any]	=		np.array(lowercase_      )
       if arr.shape[0] != arr.shape[1]:
              raise ValueError('''The input array is not a square matrix'''      )
       _lowerCamelCase							:     List[Any]	=		0
       _lowerCamelCase							:     Union[str, Any]	=		0
       _lowerCamelCase							:     Union[str, Any]	=		0
       _lowerCamelCase							:     Tuple	=		0

       # compute the shape of the output matrix
       _lowerCamelCase							:     int	=		(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							:     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							:     Union[str, Any]	=		0
              _lowerCamelCase							:     str	=		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()








import gc
import unittest

from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline
from diffusers.utils import is_flax_available, load_image, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
       import jax
       import jax.numpy as jnp
       from flax.jax_utils import replicate
       from flax.training.common_utils import shard







@slow
@require_flax
class 			__A       (      unittest.TestCase  ):




      """simple docstring"""







      def 				__snake_case			(		self):



             """simple docstring"""





             super().tearDown()
             gc.collect()


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase,  _lowerCamelCase							:     Tuple	=		FlaxControlNetModel.from_pretrained(
                 '''lllyasviel/sd-controlnet-canny'''      ,							from_pt=a__      ,							dtype=jnp.bfloataa)
             _lowerCamelCase,  _lowerCamelCase							:     Optional[Any]	=		FlaxStableDiffusionControlNetPipeline.from_pretrained(
                 '''runwayml/stable-diffusion-v1-5'''      ,							controlnet=a__      ,							from_pt=a__      ,							dtype=jnp.bfloataa)
             _lowerCamelCase							:     Union[str, Any]	=		controlnet_params

             _lowerCamelCase							:     str	=		'''bird'''
             _lowerCamelCase							:     Union[str, Any]	=		jax.device_count()
             _lowerCamelCase							:     Dict	=		pipe.prepare_text_inputs([prompts] * num_samples)

             _lowerCamelCase							:     int	=		load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png''')
             _lowerCamelCase							:     Tuple	=		pipe.prepare_image_inputs([canny_image] * num_samples)

             _lowerCamelCase							:     Union[str, Any]	=		jax.random.PRNGKey(0)
             _lowerCamelCase							:     Tuple	=		jax.random.split(a__      ,							jax.device_count())

             _lowerCamelCase							:     Dict	=		replicate(a__)
             _lowerCamelCase							:     Tuple	=		shard(a__)
             _lowerCamelCase							:     Union[str, Any]	=		shard(a__)

             _lowerCamelCase							:     Optional[Any]	=		pipe(
                 prompt_ids=a__      ,							image=a__      ,							params=a__      ,							prng_seed=a__      ,							num_inference_steps=50      ,							jit=a__      ,							).images
             assert images.shape == (jax.device_count(), 1, 768, 512, 3)

             _lowerCamelCase							:     Optional[int]	=		images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
             _lowerCamelCase							:     List[Any]	=		images[0, 253:256, 253:256, -1]

             _lowerCamelCase							:     Union[str, Any]	=		jnp.asarray(jax.device_get(image_slice.flatten()))
             _lowerCamelCase							:     Optional[int]	=		jnp.array(
                 [0.16_7969, 0.11_6699, 0.08_1543, 0.15_4297, 0.13_2812, 0.10_8887, 0.16_9922, 0.16_9922, 0.20_5078])
             print(F"""output_slice: {output_slice}""")
             assert jnp.abs(output_slice - expected_slice).max() < 1e-2



      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase,  _lowerCamelCase							:     Any	=		FlaxControlNetModel.from_pretrained(
                 '''lllyasviel/sd-controlnet-openpose'''      ,							from_pt=a__      ,							dtype=jnp.bfloataa)
             _lowerCamelCase,  _lowerCamelCase							:     Any	=		FlaxStableDiffusionControlNetPipeline.from_pretrained(
                 '''runwayml/stable-diffusion-v1-5'''      ,							controlnet=a__      ,							from_pt=a__      ,							dtype=jnp.bfloataa)
             _lowerCamelCase							:     Optional[Any]	=		controlnet_params

             _lowerCamelCase							:     Optional[Any]	=		'''Chef in the kitchen'''
             _lowerCamelCase							:     int	=		jax.device_count()
             _lowerCamelCase							:     Dict	=		pipe.prepare_text_inputs([prompts] * num_samples)

             _lowerCamelCase							:     List[Any]	=		load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png''')
             _lowerCamelCase							:     str	=		pipe.prepare_image_inputs([pose_image] * num_samples)

             _lowerCamelCase							:     Optional[Any]	=		jax.random.PRNGKey(0)
             _lowerCamelCase							:     List[str]	=		jax.random.split(a__      ,							jax.device_count())

             _lowerCamelCase							:     str	=		replicate(a__)
             _lowerCamelCase							:     Union[str, Any]	=		shard(a__)
             _lowerCamelCase							:     List[Any]	=		shard(a__)

             _lowerCamelCase							:     Any	=		pipe(
                 prompt_ids=a__      ,							image=a__      ,							params=a__      ,							prng_seed=a__      ,							num_inference_steps=50      ,							jit=a__      ,							).images
             assert images.shape == (jax.device_count(), 1, 768, 512, 3)

             _lowerCamelCase							:     int	=		images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
             _lowerCamelCase							:     Dict	=		images[0, 253:256, 253:256, -1]

             _lowerCamelCase							:     Optional[int]	=		jnp.asarray(jax.device_get(image_slice.flatten()))
             _lowerCamelCase							:     Optional[int]	=		jnp.array(
                 [[0.27_1484, 0.26_1719, 0.27_5391, 0.27_7344, 0.27_9297, 0.29_1016, 0.29_4922, 0.30_2734, 0.30_2734]])
             print(F"""output_slice: {output_slice}""")
             assert jnp.abs(output_slice - expected_slice).max() < 1e-2

