

import numpy as np
from PIL import Image


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		np.ndarray ,   _SCREAMING_SNAKE_CASE					:		int ,   _SCREAMING_SNAKE_CASE					:		int       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						np.array(_SCREAMING_SNAKE_CASE       )
    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 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		np.ndarray ,   _SCREAMING_SNAKE_CASE					:		int ,   _SCREAMING_SNAKE_CASE					:		int       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						np.array(_SCREAMING_SNAKE_CASE       )
    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
       UpperCamelCase__  :      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()








from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer



@dataclass
class       __snake_case  (    lowerCAmelCase__       ):
  __lowerCAmelCase     :	torch.FloatTensor






class       __snake_case  (    lowerCAmelCase__     , lowerCAmelCase__       ):

  @register_to_config
  def __init__(					self						,		_A = 3						,		_A = 3						,		_A = ("DownEncoderBlock2D",)						,		_A = ("UpDecoderBlock2D",)						,		_A = (64,)						,		_A = 1						,		_A = "silu"						,		_A = 3						,		_A = 32						,		_A = 256						,		_A = 32						,		_A = None						,		_A = 0.1_8_2_1_5						,		_A = "group"						,		):
      super().__init__()

      # pass init params to Encoder
      SCREAMING_SNAKE_CASE_									=						Encoder(
          in_channels=_A						,		out_channels=_A						,		down_block_types=_A						,		block_out_channels=_A						,		layers_per_block=_A						,		act_fn=_A						,		norm_num_groups=_A						,		double_z=_A						,		)

      SCREAMING_SNAKE_CASE_									=						vq_embed_dim if vq_embed_dim is not None else latent_channels

      SCREAMING_SNAKE_CASE_									=						nn.Convad(_A						,		_A						,		1)
      SCREAMING_SNAKE_CASE_									=						VectorQuantizer(_A						,		_A						,		beta=0.2_5						,		remap=_A						,		sane_index_shape=_A)
      SCREAMING_SNAKE_CASE_									=						nn.Convad(_A						,		_A						,		1)

      # pass init params to Decoder
      SCREAMING_SNAKE_CASE_									=						Decoder(
          in_channels=_A						,		out_channels=_A						,		up_block_types=_A						,		block_out_channels=_A						,		layers_per_block=_A						,		act_fn=_A						,		norm_num_groups=_A						,		norm_type=_A						,		)

  @apply_forward_hook
  def 						lowerCAmelCase__     (					self						,		_A						,		_A = True):
      SCREAMING_SNAKE_CASE_									=						self.encoder(_A)
      SCREAMING_SNAKE_CASE_									=						self.quant_conv(_A)

      if not return_dict:
          return (h,)

      return VQEncoderOutput(latents=_A)

  @apply_forward_hook
  def 						lowerCAmelCase__     (					self						,		_A						,		_A = False						,		_A = True):
      # also go through quantization layer
      if not force_not_quantize:
          SCREAMING_SNAKE_CASE_							,			SCREAMING_SNAKE_CASE_							,			SCREAMING_SNAKE_CASE_									=						self.quantize(_A)
      else:
          SCREAMING_SNAKE_CASE_									=						h
      SCREAMING_SNAKE_CASE_									=						self.post_quant_conv(_A)
      SCREAMING_SNAKE_CASE_									=						self.decoder(_A						,		quant if self.config.norm_type == 'spatial' else None)

      if not return_dict:
          return (dec,)

      return DecoderOutput(sample=_A)


  def 						lowerCAmelCase__     (					self						,		_A						,		_A = True):
      SCREAMING_SNAKE_CASE_									=						sample
      SCREAMING_SNAKE_CASE_									=						self.encode(_A).latents
      SCREAMING_SNAKE_CASE_									=						self.decode(_A).sample

      if not return_dict:
          return (dec,)

      return DecoderOutput(sample=_A)


