

'''simple docstring'''
import inspect
from typing import List, Optional, Tuple, Union

import numpy as np
import PIL
import torch
import torch.utils.checkpoint

from ...models import UNetaDModel, VQModel
from ...schedulers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


def        _lowerCAmelCase					(						_UpperCamelCase						:     Optional[int]				)      ->			str:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =image.size
     _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =(x - x % 32 for x in (w, h))  # resize to integer multiple of 32
     _SCREAMING_SNAKE_CASE							    =image.resize((w, h)							, resample=PIL_INTERPOLATION['lanczos']				)
     _SCREAMING_SNAKE_CASE							    =np.array(_UpperCamelCase				).astype(np.floataa				) / 2_55.0
     _SCREAMING_SNAKE_CASE							    =image[None].transpose(0							, 3							, 1							, 2				)
     _SCREAMING_SNAKE_CASE							    =torch.from_numpy(_UpperCamelCase				)
     return 2.0 * image - 1.0







class 							A__    (       A__  ):





  def __init__(		self      :	Tuple							,					_a      :	VQModel							,					_a      :	UNetaDModel							,					_a      :	Union[
          DDIMScheduler,
          PNDMScheduler,
          LMSDiscreteScheduler,
          EulerDiscreteScheduler,
          EulerAncestralDiscreteScheduler,
          DPMSolverMultistepScheduler,
      ]							,					)	->    int:





       '''simple docstring'''






       super().__init__()
       self.register_modules(vqvae=_a							,					unet=_a							,					scheduler=_a )





  @torch.no_grad()
  def __call__(		self      :	Any							,					_a      :	Union[torch.Tensor, PIL.Image.Image] = None							,					_a      :	Optional[int] = 1							,					_a      :	Optional[int] = 100							,					_a      :	Optional[float] = 0.0							,					_a      :	Optional[Union[torch.Generator, List[torch.Generator]]] = None							,					_a      :	Optional[str] = "pil"							,					_a      :	bool = True							,					)	->    Union[Tuple, ImagePipelineOutput]:





       '''simple docstring'''






       if isinstance(_a							,					PIL.Image.Image ):
            _SCREAMING_SNAKE_CASE							    =1
       elif isinstance(_a							,					torch.Tensor ):
            _SCREAMING_SNAKE_CASE							    =image.shape[0]
       else:
            raise ValueError(f"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_a )}" )

       if isinstance(_a							,					PIL.Image.Image ):
            _SCREAMING_SNAKE_CASE							    =preprocess(_a )

       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =image.shape[-2:]

       # in_channels should be 6: 3 for latents, 3 for low resolution image
       _SCREAMING_SNAKE_CASE							    =(batch_size, self.unet.config.in_channels // 2, height, width)
       _SCREAMING_SNAKE_CASE							    =next(self.unet.parameters() ).dtype

       _SCREAMING_SNAKE_CASE							    =randn_tensor(_a							,					generator=_a							,					device=self.device							,					dtype=_a )

       _SCREAMING_SNAKE_CASE							    =image.to(device=self.device							,					dtype=_a )

       # set timesteps and move to the correct device
       self.scheduler.set_timesteps(_a							,					device=self.device )
       _SCREAMING_SNAKE_CASE							    =self.scheduler.timesteps

       # scale the initial noise by the standard deviation required by the scheduler
       _SCREAMING_SNAKE_CASE							    =latents * self.scheduler.init_noise_sigma

       # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
       # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
       # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
       # and should be between [0, 1]
       _SCREAMING_SNAKE_CASE							    ='eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
       _SCREAMING_SNAKE_CASE							    ={}
       if accepts_eta:
            _SCREAMING_SNAKE_CASE							    =eta

       for t in self.progress_bar(_a ):
            # concat latents and low resolution image in the channel dimension.
            _SCREAMING_SNAKE_CASE							    =torch.cat([latents, image]							,					dim=1 )
            _SCREAMING_SNAKE_CASE							    =self.scheduler.scale_model_input(_a							,					_a )
            # predict the noise residual
            _SCREAMING_SNAKE_CASE							    =self.unet(_a							,					_a ).sample
            # compute the previous noisy sample x_t -> x_t-1
            _SCREAMING_SNAKE_CASE							    =self.scheduler.step(_a							,					_a							,					_a							,					**_a ).prev_sample

       # decode the image latents with the VQVAE
       _SCREAMING_SNAKE_CASE							    =self.vqvae.decode(_a ).sample
       _SCREAMING_SNAKE_CASE							    =torch.clamp(_a							,					-1.0							,					1.0 )
       _SCREAMING_SNAKE_CASE							    =image / 2 + 0.5
       _SCREAMING_SNAKE_CASE							    =image.cpu().permute(0							,					2							,					3							,					1 ).numpy()

       if output_type == "pil":
            _SCREAMING_SNAKE_CASE							    =self.numpy_to_pil(_a )

       if not return_dict:
            return (image,)

       return ImagePipelineOutput(images=_a )



'''simple docstring'''
import numpy as np
from PIL import Image


def        _lowerCAmelCase					(						_UpperCamelCase						:     np.ndarray							, _UpperCamelCase						:     int							, _UpperCamelCase						:     int				)      ->			np.ndarray:
     """simple docstring"""




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

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

     return updated_arr


def        _lowerCAmelCase					(						_UpperCamelCase						:     np.ndarray							, _UpperCamelCase						:     int							, _UpperCamelCase						:     int				)      ->			np.ndarray:
     """simple docstring"""




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

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

     return updated_arr


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

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

     # Loading the image
     lowerCamelCase :      Optional[Any]					 =     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()
