
"""simple docstring"""






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 __A						(   a_ :							str		,		a_ :							List[Any]     )->							Optional[Any]:




		'''simple docstring'''






		SCREAMING_SNAKE_CASE       :     Tuple				= checkpoint

		SCREAMING_SNAKE_CASE       :     int				= {}

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

		SCREAMING_SNAKE_CASE       :     List[str]				= vae_state_dict['''decoder.conv_in.weight''']
		SCREAMING_SNAKE_CASE       :     Any				= vae_state_dict['''decoder.conv_in.bias''']
		SCREAMING_SNAKE_CASE       :     List[Any]				= vae_state_dict['''decoder.conv_out.weight''']
		SCREAMING_SNAKE_CASE       :     Dict				= vae_state_dict['''decoder.conv_out.bias''']
		SCREAMING_SNAKE_CASE       :     Union[str, Any]				= vae_state_dict['''decoder.norm_out.weight''']
		SCREAMING_SNAKE_CASE       :     Dict				= vae_state_dict['''decoder.norm_out.bias''']

		SCREAMING_SNAKE_CASE       :     Optional[Any]				= vae_state_dict['''quant_conv.weight''']
		SCREAMING_SNAKE_CASE       :     List[str]				= vae_state_dict['''quant_conv.bias''']
		SCREAMING_SNAKE_CASE       :     Optional[int]				= vae_state_dict['''post_quant_conv.weight''']
		SCREAMING_SNAKE_CASE       :     str				= vae_state_dict['''post_quant_conv.bias''']

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

		# Retrieves the keys for the decoder up blocks only
		SCREAMING_SNAKE_CASE       :     Any				= len({'''.'''.join(layer.split('''.'''     )[:3]     ) for layer in vae_state_dict if '''decoder.up''' in layer}     )
		SCREAMING_SNAKE_CASE       :     Union[str, Any]				= {
		    layer_id: [key for key in vae_state_dict if F"up.{layer_id}" in key] for layer_id in range(a_     )
		}

		for i in range(a_     ):
				SCREAMING_SNAKE_CASE       :     Any				= [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:
						SCREAMING_SNAKE_CASE       :     List[str]				= vae_state_dict.pop(
						    F"encoder.down.{i}.downsample.conv.weight"     )
						SCREAMING_SNAKE_CASE       :     Optional[int]				= vae_state_dict.pop(
						    F"encoder.down.{i}.downsample.conv.bias"     )

				SCREAMING_SNAKE_CASE       :     str				= renew_vae_resnet_paths(a_     )
				SCREAMING_SNAKE_CASE       :     Optional[Any]				= {'''old''': F"down.{i}.block", '''new''': F"down_blocks.{i}.resnets"}
				assign_to_checkpoint(a_		,		a_		,		a_		,		additional_replacements=[meta_path]		,		config=a_     )

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

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

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

		for i in range(a_     ):
				SCREAMING_SNAKE_CASE       :     Optional[Any]				= num_up_blocks - 1 - i
				SCREAMING_SNAKE_CASE       :     Union[str, Any]				= [
				    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:
						SCREAMING_SNAKE_CASE       :     Tuple				= vae_state_dict[
						    F"decoder.up.{block_id}.upsample.conv.weight"
						]
						SCREAMING_SNAKE_CASE       :     List[str]				= vae_state_dict[
						    F"decoder.up.{block_id}.upsample.conv.bias"
						]

				SCREAMING_SNAKE_CASE       :     List[str]				= renew_vae_resnet_paths(a_     )
				SCREAMING_SNAKE_CASE       :     str				= {'''old''': F"up.{block_id}.block", '''new''': F"up_blocks.{i}.resnets"}
				assign_to_checkpoint(a_		,		a_		,		a_		,		additional_replacements=[meta_path]		,		config=a_     )

		SCREAMING_SNAKE_CASE       :     Dict				= [key for key in vae_state_dict if '''decoder.mid.block''' in key]
		SCREAMING_SNAKE_CASE       :     Any				= 2
		for i in range(1		,		num_mid_res_blocks + 1     ):
				SCREAMING_SNAKE_CASE       :     Optional[Any]				= [key for key in mid_resnets if F"decoder.mid.block_{i}" in key]

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

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





def __A						(   a_ :							str		,		a_ :							str		,		)->							Union[str, Any]:




		'''simple docstring'''






		SCREAMING_SNAKE_CASE       :     Optional[int]				= requests.get(
		    ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'''     )
		SCREAMING_SNAKE_CASE       :     Union[str, Any]				= io.BytesIO(r.content     )

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

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

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

		SCREAMING_SNAKE_CASE       :     Dict				= AutoencoderKL(**a_     )
		vae.load_state_dict(a_     )
		vae.save_pretrained(a_     )


if __name__ == "__main__":
					lowerCamelCase__ :       Any						     =			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__ :       Any						     =			parser.parse_args()

					vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)







"""simple docstring"""






from __future__ import annotations

from fractions import Fraction





def __A						(   a_ :							int		,		a_ :							int     )->							bool:




		'''simple docstring'''






		return (
		    num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
		)





def __A						(   a_ :							int     )->							list[str]:




		'''simple docstring'''






		SCREAMING_SNAKE_CASE       :     Union[str, Any]				= []
		SCREAMING_SNAKE_CASE       :     List[str]				= 11
		SCREAMING_SNAKE_CASE       :     Union[str, Any]				= int('''1''' + '''0''' * digit_len     )
		for num in range(a_		,		a_     ):
				while den <= 99:
						if (num != den) and (num % 10 == den // 10) and (den % 10 != 0):
								if is_digit_cancelling(a_		,		a_     ):
										solutions.append(F"{num}/{den}"     )
						den += 1
				num += 1
				SCREAMING_SNAKE_CASE       :     Optional[Any]				= 10
		return solutions





def __A						(   a_ :							int = 2     )->							int:




		'''simple docstring'''






		SCREAMING_SNAKE_CASE       :     Optional[Any]				= 1.0
		for fraction in fraction_list(a_     ):
				SCREAMING_SNAKE_CASE       :     List[str]				= Fraction(a_     )
				result *= frac.denominator / frac.numerator
		return int(a_     )


if __name__ == "__main__":
					print(solution())





