"""simple docstring"""




import argparse
import os

import torch

from transformers import FlavaImageCodebook, FlavaImageCodebookConfig






def   UpperCAmelCase					(	UpperCamelCase__       ,    UpperCamelCase__       ,    UpperCamelCase__       ,    UpperCamelCase__				):






							"""simple docstring"""





							A__	     =							s.rsplit(__lowerCAmelCase       ,    __lowerCAmelCase				)
							return new.join(__lowerCAmelCase				)






def   UpperCAmelCase					(	UpperCamelCase__				):






							"""simple docstring"""





							return sum(param.float().sum() if 'encoder.embeddings' not in key else 0 for key, param in state_dict.items()				)






def   UpperCAmelCase					(	UpperCamelCase__				):






							"""simple docstring"""





							A__	     =							{}

							A__	     =							['group_1', 'group_2', 'group_3', 'group_4']
							for key, value in state_dict.items():
														for group_key in group_keys:
																					if group_key in key:
																												A__	     =							key.replace(F'''{group_key}.'''       ,    F'''{group_key}.group.'''				)

														if "res_path" in key:
																					A__	     =							key.replace('res_path.'       ,    'res_path.path.'				)

														if key.endswith('.w'				):
																					A__	     =							rreplace(__lowerCAmelCase       ,    '.w'       ,    '.weight'       ,    1				)
														if key.endswith('.b'				):
																					A__	     =							rreplace(__lowerCAmelCase       ,    '.b'       ,    '.bias'       ,    1				)

														A__	     =							value.float()

							return upgrade






@torch.no_grad()
def   UpperCAmelCase					(	UpperCamelCase__       ,    UpperCamelCase__       ,    UpperCamelCase__=None       ,    UpperCamelCase__=True				):






							"""simple docstring"""





							from dall_e import Encoder

							A__	     =							Encoder()
							if os.path.exists(__lowerCAmelCase				):
														A__	     =							torch.load(__lowerCAmelCase				)
							else:
														A__	     =							torch.hub.load_state_dict_from_url(__lowerCAmelCase				)

							if isinstance(__lowerCAmelCase       ,    __lowerCAmelCase				):
														A__	     =							ckpt.state_dict()
							encoder.load_state_dict(__lowerCAmelCase				)

							if config_path is not None:
														A__	     =							FlavaImageCodebookConfig.from_pretrained(__lowerCAmelCase				)
							else:
														A__	     =							FlavaImageCodebookConfig()

							A__	     =							FlavaImageCodebook(__lowerCAmelCase				).eval()
							A__	     =							encoder.state_dict()

							A__	     =							upgrade_state_dict(__lowerCAmelCase				)
							hf_model.load_state_dict(__lowerCAmelCase				)
							A__	     =							hf_model.state_dict()
							A__	     =							count_parameters(__lowerCAmelCase				)
							A__	     =							count_parameters(__lowerCAmelCase				)

							assert torch.allclose(__lowerCAmelCase       ,    __lowerCAmelCase       ,    atol=1E-3				)

							if save_checkpoint:
														hf_model.save_pretrained(__lowerCAmelCase				)
							else:
														return hf_state_dict


if __name__ == "__main__":
				__lowerCamelCase											=  argparse.ArgumentParser()
				parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
				parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to flava checkpoint")
				parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
				__lowerCamelCase											=  parser.parse_args()

				convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)






"""simple docstring"""




import numpy as np
from PIL import Image






def   UpperCAmelCase					(	UpperCamelCase__       ,    UpperCamelCase__       ,    UpperCamelCase__				):






							"""simple docstring"""





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

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

							return updated_arr






def   UpperCAmelCase					(	UpperCamelCase__       ,    UpperCamelCase__       ,    UpperCamelCase__				):






							"""simple docstring"""





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

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





