






import argparse
import io

import requests
import torch
from omegaconf import OmegaConf

from diffusers import AutoencoderKL
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
    assign_to_checkpoint,
    conv_attn_to_linear,
    create_vae_diffusers_config,
    renew_vae_attention_paths,
    renew_vae_resnet_paths,
)





def 		_UpperCAmelCase   (							__A							:   Optional[Any]						,		__A							:   Any      ):
				a_		:  Optional[Any]											=      checkpoint

				a_		:  Optional[int]											=      {}

				a_		:  Union[str, Any]											=      vae_state_dict['''encoder.conv_in.weight''']
				a_		:  Optional[int]											=      vae_state_dict['''encoder.conv_in.bias''']
				a_		:  Dict											=      vae_state_dict['''encoder.conv_out.weight''']
				a_		:  Optional[int]											=      vae_state_dict['''encoder.conv_out.bias''']
				a_		:  List[str]											=      vae_state_dict['''encoder.norm_out.weight''']
				a_		:  List[Any]											=      vae_state_dict['''encoder.norm_out.bias''']

				a_		:  Any											=      vae_state_dict['''decoder.conv_in.weight''']
				a_		:  Tuple											=      vae_state_dict['''decoder.conv_in.bias''']
				a_		:  List[str]											=      vae_state_dict['''decoder.conv_out.weight''']
				a_		:  List[str]											=      vae_state_dict['''decoder.conv_out.bias''']
				a_		:  Optional[int]											=      vae_state_dict['''decoder.norm_out.weight''']
				a_		:  Tuple											=      vae_state_dict['''decoder.norm_out.bias''']

				a_		:  Dict											=      vae_state_dict['''quant_conv.weight''']
				a_		:  str											=      vae_state_dict['''quant_conv.bias''']
				a_		:  List[Any]											=      vae_state_dict['''post_quant_conv.weight''']
				a_		:  List[str]											=      vae_state_dict['''post_quant_conv.bias''']

				# Retrieves the keys for the encoder down blocks only
				a_		:  Any											=      len({'''.'''.join(layer.split('''.'''      )[:3]      ) for layer in vae_state_dict if '''encoder.down''' in layer}      )
				a_		:  Any											=      {
				    layer_id: [key for key in vae_state_dict if f'down.{layer_id}' in key] for layer_id in range(UpperCAmelCase__      )
				}

				# Retrieves the keys for the decoder up blocks only
				a_		:  Tuple											=      len({'''.'''.join(layer.split('''.'''      )[:3]      ) for layer in vae_state_dict if '''decoder.up''' in layer}      )
				a_		:  Optional[int]											=      {
				    layer_id: [key for key in vae_state_dict if f'up.{layer_id}' in key] for layer_id in range(UpperCAmelCase__      )
				}

				for i in range(UpperCAmelCase__      ):
								a_		:  List[str]											=      [key for key in down_blocks[i] if f'down.{i}' in key and f'down.{i}.downsample' not in key]

								if f'encoder.down.{i}.downsample.conv.weight' in vae_state_dict:
												a_		:  Optional[int]											=      vae_state_dict.pop(
												    f'encoder.down.{i}.downsample.conv.weight'      )
												a_		:  List[Any]											=      vae_state_dict.pop(
												    f'encoder.down.{i}.downsample.conv.bias'      )

								a_		:  Union[str, Any]											=      renew_vae_resnet_paths(UpperCAmelCase__      )
								a_		:  List[str]											=      {'''old''': f'down.{i}.block', '''new''': f'down_blocks.{i}.resnets'}
								assign_to_checkpoint(UpperCAmelCase__						,		UpperCAmelCase__						,		UpperCAmelCase__						,		additional_replacements=[meta_path]						,		config=UpperCAmelCase__      )

				a_		:  Optional[Any]											=      [key for key in vae_state_dict if '''encoder.mid.block''' in key]
				a_		:  str											=      2
				for i in range(1						,		num_mid_res_blocks + 1      ):
								a_		:  Union[str, Any]											=      [key for key in mid_resnets if f'encoder.mid.block_{i}' in key]

								a_		:  List[Any]											=      renew_vae_resnet_paths(UpperCAmelCase__      )
								a_		:  List[str]											=      {'''old''': f'mid.block_{i}', '''new''': f'mid_block.resnets.{i - 1}'}
								assign_to_checkpoint(UpperCAmelCase__						,		UpperCAmelCase__						,		UpperCAmelCase__						,		additional_replacements=[meta_path]						,		config=UpperCAmelCase__      )

				a_		:  Any											=      [key for key in vae_state_dict if '''encoder.mid.attn''' in key]
				a_		:  int											=      renew_vae_attention_paths(UpperCAmelCase__      )
				a_		:  List[str]											=      {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''}
				assign_to_checkpoint(UpperCAmelCase__						,		UpperCAmelCase__						,		UpperCAmelCase__						,		additional_replacements=[meta_path]						,		config=UpperCAmelCase__      )
				conv_attn_to_linear(UpperCAmelCase__      )

				for i in range(UpperCAmelCase__      ):
								a_		:  List[str]											=      num_up_blocks - 1 - i
								a_		:  List[str]											=      [
								    key for key in up_blocks[block_id] if f'up.{block_id}' in key and f'up.{block_id}.upsample' not in key
								]

								if f'decoder.up.{block_id}.upsample.conv.weight' in vae_state_dict:
												a_		:  int											=      vae_state_dict[
												    f'decoder.up.{block_id}.upsample.conv.weight'
												]
												a_		:  Union[str, Any]											=      vae_state_dict[
												    f'decoder.up.{block_id}.upsample.conv.bias'
												]

								a_		:  Optional[Any]											=      renew_vae_resnet_paths(UpperCAmelCase__      )
								a_		:  Optional[Any]											=      {'''old''': f'up.{block_id}.block', '''new''': f'up_blocks.{i}.resnets'}
								assign_to_checkpoint(UpperCAmelCase__						,		UpperCAmelCase__						,		UpperCAmelCase__						,		additional_replacements=[meta_path]						,		config=UpperCAmelCase__      )

				a_		:  int											=      [key for key in vae_state_dict if '''decoder.mid.block''' in key]
				a_		:  int											=      2
				for i in range(1						,		num_mid_res_blocks + 1      ):
								a_		:  Tuple											=      [key for key in mid_resnets if f'decoder.mid.block_{i}' in key]

								a_		:  int											=      renew_vae_resnet_paths(UpperCAmelCase__      )
								a_		:  int											=      {'''old''': f'mid.block_{i}', '''new''': f'mid_block.resnets.{i - 1}'}
								assign_to_checkpoint(UpperCAmelCase__						,		UpperCAmelCase__						,		UpperCAmelCase__						,		additional_replacements=[meta_path]						,		config=UpperCAmelCase__      )

				a_		:  str											=      [key for key in vae_state_dict if '''decoder.mid.attn''' in key]
				a_		:  Dict											=      renew_vae_attention_paths(UpperCAmelCase__      )
				a_		:  Tuple											=      {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''}
				assign_to_checkpoint(UpperCAmelCase__						,		UpperCAmelCase__						,		UpperCAmelCase__						,		additional_replacements=[meta_path]						,		config=UpperCAmelCase__      )
				conv_attn_to_linear(UpperCAmelCase__      )
				return new_checkpoint





def 		_UpperCAmelCase   (							__A							:   str						,		__A							:   str						,		):
				# Only support V1
				a_		:  Any											=      requests.get(
				    ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'''      )
				a_		:  str											=      io.BytesIO(r.content      )

				a_		:  str											=      OmegaConf.load(UpperCAmelCase__      )
				a_		:  Optional[Any]											=      5_12
				a_		:  Union[str, Any]											=      '''cuda''' if torch.cuda.is_available() else '''cpu'''
				if checkpoint_path.endswith('''safetensors'''      ):
								from safetensors import safe_open

								a_		:  List[str]											=      {}
								with safe_open(UpperCAmelCase__						,		framework='''pt'''						,		device='''cpu'''      ) as f:
												for key in f.keys():
																a_		:  Optional[int]											=      f.get_tensor(UpperCAmelCase__      )
				else:
								a_		:  Dict											=      torch.load(UpperCAmelCase__						,		map_location=UpperCAmelCase__      )['''state_dict''']

				# Convert the VAE model.
				a_		:  Union[str, Any]											=      create_vae_diffusers_config(UpperCAmelCase__						,		image_size=UpperCAmelCase__      )
				a_		:  List[str]											=      custom_convert_ldm_vae_checkpoint(UpperCAmelCase__						,		UpperCAmelCase__      )

				a_		:  int											=      AutoencoderKL(**UpperCAmelCase__      )
				vae.load_state_dict(UpperCAmelCase__      )
				vae.save_pretrained(UpperCAmelCase__      )


if __name__ == "__main__":
		__lowerCAmelCase       		=      argparse.ArgumentParser()

		parser.add_argument('--vae_pt_path', default=None, type=str, required=True, help='Path to the VAE.pt to convert.')
		parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the VAE.pt to convert.')

		__lowerCAmelCase       		=      parser.parse_args()

		vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)












'''simple docstring'''







import re
import string

import numpy as np

import datasets


__lowerCAmelCase       		=      '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

__lowerCAmelCase       		=      '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

__lowerCAmelCase       		=      '\n'





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,   _KWARGS_DESCRIPTION       )
class 	SCREAMING_SNAKE_CASE					(					datasets.Metric       ):






			def 			SCREAMING_SNAKE_CASE      ( self      :			Optional[Any]					)			->			int:
							return datasets.MetricInfo(
							    description=_DESCRIPTION  ,						citation=_CITATION  ,						inputs_description=_KWARGS_DESCRIPTION  ,						features=datasets.Features(
							        {
							            '''predictions''': datasets.Value('''string'''  ,						id='''sequence'''					),
							            '''references''': datasets.Value('''string'''  ,						id='''sequence'''					),
							        }					)  ,						reference_urls=[]  ,						)







			def 			SCREAMING_SNAKE_CASE      ( self      :			str  ,						__SCREAMING_SNAKE_CASE      :			List[Any]  ,						__SCREAMING_SNAKE_CASE      :			Optional[int]  ,						__SCREAMING_SNAKE_CASE      :			Dict=None  ,						__SCREAMING_SNAKE_CASE      :			int=False  ,						__SCREAMING_SNAKE_CASE      :			Optional[int]=False  ,						__SCREAMING_SNAKE_CASE      :			Dict=False  ,						)			->			str:
							if regexes_to_ignore is not None:
											for s in regexes_to_ignore:
															a_		:  Optional[Any]											=      np.array([re.sub(__SCREAMING_SNAKE_CASE  ,						''''''  ,						__SCREAMING_SNAKE_CASE					) for x in predictions]					)
															a_		:  int											=      np.array([re.sub(__SCREAMING_SNAKE_CASE  ,						''''''  ,						__SCREAMING_SNAKE_CASE					) for x in references]					)
							else:
											a_		:  List[str]											=      np.asarray(__SCREAMING_SNAKE_CASE					)
											a_		:  Any											=      np.asarray(__SCREAMING_SNAKE_CASE					)

							if ignore_case:
											a_		:  List[str]											=      np.char.lower(__SCREAMING_SNAKE_CASE					)
											a_		:  List[Any]											=      np.char.lower(__SCREAMING_SNAKE_CASE					)

							if ignore_punctuation:
											a_		:  Any											=      string.punctuation.maketrans(''''''  ,						''''''  ,						string.punctuation					)
											a_		:  Union[str, Any]											=      np.char.translate(__SCREAMING_SNAKE_CASE  ,						table=__SCREAMING_SNAKE_CASE					)
											a_		:  int											=      np.char.translate(__SCREAMING_SNAKE_CASE  ,						table=__SCREAMING_SNAKE_CASE					)

							if ignore_numbers:
											a_		:  int											=      string.digits.maketrans(''''''  ,						''''''  ,						string.digits					)
											a_		:  Optional[int]											=      np.char.translate(__SCREAMING_SNAKE_CASE  ,						table=__SCREAMING_SNAKE_CASE					)
											a_		:  Dict											=      np.char.translate(__SCREAMING_SNAKE_CASE  ,						table=__SCREAMING_SNAKE_CASE					)

							a_		:  Optional[Any]											=      predictions == references

							return {"exact_match": np.mean(__SCREAMING_SNAKE_CASE					) * 100}




