

'''simple docstring'''
import flax.linen as nn
import jax.numpy as jnp

from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD







class 							A__    (       nn.Module  ):
  A__		 =				42
  A__		 =				42
  A__		 =				0.0
  A__		 =				1
  A__		 =				1
  A__		 =				True
  A__		 =				False
  A__		 =				False
  A__		 =				False
  A__		 =				jnp.floataa





  def 						A  (		self      :	str )	->    List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =[]
       _SCREAMING_SNAKE_CASE							    =[]

       for i in range(self.num_layers ):
            _SCREAMING_SNAKE_CASE							    =self.in_channels if i == 0 else self.out_channels

            _SCREAMING_SNAKE_CASE							    =FlaxResnetBlockaD(
                in_channels=_a							,					out_channels=self.out_channels							,					dropout_prob=self.dropout							,					dtype=self.dtype							,					)
            resnets.append(_a )

            _SCREAMING_SNAKE_CASE							    =FlaxTransformeraDModel(
                in_channels=self.out_channels							,					n_heads=self.num_attention_heads							,					d_head=self.out_channels // self.num_attention_heads							,					depth=1							,					use_linear_projection=self.use_linear_projection							,					only_cross_attention=self.only_cross_attention							,					use_memory_efficient_attention=self.use_memory_efficient_attention							,					dtype=self.dtype							,					)
            attentions.append(_a )

       _SCREAMING_SNAKE_CASE							    =resnets
       _SCREAMING_SNAKE_CASE							    =attentions

       if self.add_downsample:
            _SCREAMING_SNAKE_CASE							    =FlaxDownsampleaD(self.out_channels							,					dtype=self.dtype )





  def __call__(		self      :	Dict							,					_a      :	Union[str, Any]							,					_a      :	Union[str, Any]							,					_a      :	str							,					_a      :	Optional[Any]=True )	->    List[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =()

       for resnet, attn in zip(self.resnets							,					self.attentions ):
            _SCREAMING_SNAKE_CASE							    =resnet(_a							,					_a							,					deterministic=_a )
            _SCREAMING_SNAKE_CASE							    =attn(_a							,					_a							,					deterministic=_a )
            output_states += (hidden_states,)

       if self.add_downsample:
            _SCREAMING_SNAKE_CASE							    =self.downsamplers_a(_a )
            output_states += (hidden_states,)

       return hidden_states, output_states







class 							A__    (       nn.Module  ):
  A__		 =				42
  A__		 =				42
  A__		 =				0.0
  A__		 =				1
  A__		 =				True
  A__		 =				jnp.floataa





  def 						A  (		self      :	Dict )	->    Union[str, Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =[]

       for i in range(self.num_layers ):
            _SCREAMING_SNAKE_CASE							    =self.in_channels if i == 0 else self.out_channels

            _SCREAMING_SNAKE_CASE							    =FlaxResnetBlockaD(
                in_channels=_a							,					out_channels=self.out_channels							,					dropout_prob=self.dropout							,					dtype=self.dtype							,					)
            resnets.append(_a )
       _SCREAMING_SNAKE_CASE							    =resnets

       if self.add_downsample:
            _SCREAMING_SNAKE_CASE							    =FlaxDownsampleaD(self.out_channels							,					dtype=self.dtype )





  def __call__(		self      :	Dict							,					_a      :	int							,					_a      :	Tuple							,					_a      :	Union[str, Any]=True )	->    int:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =()

       for resnet in self.resnets:
            _SCREAMING_SNAKE_CASE							    =resnet(_a							,					_a							,					deterministic=_a )
            output_states += (hidden_states,)

       if self.add_downsample:
            _SCREAMING_SNAKE_CASE							    =self.downsamplers_a(_a )
            output_states += (hidden_states,)

       return hidden_states, output_states







class 							A__    (       nn.Module  ):
  A__		 =				42
  A__		 =				42
  A__		 =				42
  A__		 =				0.0
  A__		 =				1
  A__		 =				1
  A__		 =				True
  A__		 =				False
  A__		 =				False
  A__		 =				False
  A__		 =				jnp.floataa





  def 						A  (		self      :	int )	->    Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =[]
       _SCREAMING_SNAKE_CASE							    =[]

       for i in range(self.num_layers ):
            _SCREAMING_SNAKE_CASE							    =self.in_channels if (i == self.num_layers - 1) else self.out_channels
            _SCREAMING_SNAKE_CASE							    =self.prev_output_channel if i == 0 else self.out_channels

            _SCREAMING_SNAKE_CASE							    =FlaxResnetBlockaD(
                in_channels=resnet_in_channels + res_skip_channels							,					out_channels=self.out_channels							,					dropout_prob=self.dropout							,					dtype=self.dtype							,					)
            resnets.append(_a )

            _SCREAMING_SNAKE_CASE							    =FlaxTransformeraDModel(
                in_channels=self.out_channels							,					n_heads=self.num_attention_heads							,					d_head=self.out_channels // self.num_attention_heads							,					depth=1							,					use_linear_projection=self.use_linear_projection							,					only_cross_attention=self.only_cross_attention							,					use_memory_efficient_attention=self.use_memory_efficient_attention							,					dtype=self.dtype							,					)
            attentions.append(_a )

       _SCREAMING_SNAKE_CASE							    =resnets
       _SCREAMING_SNAKE_CASE							    =attentions

       if self.add_upsample:
            _SCREAMING_SNAKE_CASE							    =FlaxUpsampleaD(self.out_channels							,					dtype=self.dtype )





  def __call__(		self      :	Optional[Any]							,					_a      :	Optional[Any]							,					_a      :	Dict							,					_a      :	Union[str, Any]							,					_a      :	str							,					_a      :	List[str]=True )	->    int:





       '''simple docstring'''






       for resnet, attn in zip(self.resnets							,					self.attentions ):
            # pop res hidden states
            _SCREAMING_SNAKE_CASE							    =res_hidden_states_tuple[-1]
            _SCREAMING_SNAKE_CASE							    =res_hidden_states_tuple[:-1]
            _SCREAMING_SNAKE_CASE							    =jnp.concatenate((hidden_states, res_hidden_states)							,					axis=-1 )

            _SCREAMING_SNAKE_CASE							    =resnet(_a							,					_a							,					deterministic=_a )
            _SCREAMING_SNAKE_CASE							    =attn(_a							,					_a							,					deterministic=_a )

       if self.add_upsample:
            _SCREAMING_SNAKE_CASE							    =self.upsamplers_a(_a )

       return hidden_states







class 							A__    (       nn.Module  ):
  A__		 =				42
  A__		 =				42
  A__		 =				42
  A__		 =				0.0
  A__		 =				1
  A__		 =				True
  A__		 =				jnp.floataa





  def 						A  (		self      :	Optional[int] )	->    Union[str, Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =[]

       for i in range(self.num_layers ):
            _SCREAMING_SNAKE_CASE							    =self.in_channels if (i == self.num_layers - 1) else self.out_channels
            _SCREAMING_SNAKE_CASE							    =self.prev_output_channel if i == 0 else self.out_channels

            _SCREAMING_SNAKE_CASE							    =FlaxResnetBlockaD(
                in_channels=resnet_in_channels + res_skip_channels							,					out_channels=self.out_channels							,					dropout_prob=self.dropout							,					dtype=self.dtype							,					)
            resnets.append(_a )

       _SCREAMING_SNAKE_CASE							    =resnets

       if self.add_upsample:
            _SCREAMING_SNAKE_CASE							    =FlaxUpsampleaD(self.out_channels							,					dtype=self.dtype )





  def __call__(		self      :	str							,					_a      :	Dict							,					_a      :	Dict							,					_a      :	Optional[Any]							,					_a      :	str=True )	->    Optional[int]:





       '''simple docstring'''






       for resnet in self.resnets:
            # pop res hidden states
            _SCREAMING_SNAKE_CASE							    =res_hidden_states_tuple[-1]
            _SCREAMING_SNAKE_CASE							    =res_hidden_states_tuple[:-1]
            _SCREAMING_SNAKE_CASE							    =jnp.concatenate((hidden_states, res_hidden_states)							,					axis=-1 )

            _SCREAMING_SNAKE_CASE							    =resnet(_a							,					_a							,					deterministic=_a )

       if self.add_upsample:
            _SCREAMING_SNAKE_CASE							    =self.upsamplers_a(_a )

       return hidden_states







class 							A__    (       nn.Module  ):
  A__		 =				42
  A__		 =				0.0
  A__		 =				1
  A__		 =				1
  A__		 =				False
  A__		 =				False
  A__		 =				jnp.floataa





  def 						A  (		self      :	List[str] )	->    Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =[
           FlaxResnetBlockaD(
               in_channels=self.in_channels							,					out_channels=self.in_channels							,					dropout_prob=self.dropout							,					dtype=self.dtype							,					)
       ]

       _SCREAMING_SNAKE_CASE							    =[]

       for _ in range(self.num_layers ):
            _SCREAMING_SNAKE_CASE							    =FlaxTransformeraDModel(
                in_channels=self.in_channels							,					n_heads=self.num_attention_heads							,					d_head=self.in_channels // self.num_attention_heads							,					depth=1							,					use_linear_projection=self.use_linear_projection							,					use_memory_efficient_attention=self.use_memory_efficient_attention							,					dtype=self.dtype							,					)
            attentions.append(_a )

            _SCREAMING_SNAKE_CASE							    =FlaxResnetBlockaD(
                in_channels=self.in_channels							,					out_channels=self.in_channels							,					dropout_prob=self.dropout							,					dtype=self.dtype							,					)
            resnets.append(_a )

       _SCREAMING_SNAKE_CASE							    =resnets
       _SCREAMING_SNAKE_CASE							    =attentions





  def __call__(		self      :	Union[str, Any]							,					_a      :	List[Any]							,					_a      :	Tuple							,					_a      :	Optional[Any]							,					_a      :	str=True )	->    Union[str, Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.resnets[0](_a							,					_a )
       for attn, resnet in zip(self.attentions							,					self.resnets[1:] ):
            _SCREAMING_SNAKE_CASE							    =attn(_a							,					_a							,					deterministic=_a )
            _SCREAMING_SNAKE_CASE							    =resnet(_a							,					_a							,					deterministic=_a )

       return hidden_states



'''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()
