


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 							__lowercase   ( __lowerCAmelCase							:				List[str]					,    __lowerCAmelCase							:				Any   ):
							a__             =     checkpoint

							a__             =     {}

							a__             =     vae_state_dict['encoder.conv_in.weight']
							a__             =     vae_state_dict['encoder.conv_in.bias']
							a__             =     vae_state_dict['encoder.conv_out.weight']
							a__             =     vae_state_dict['encoder.conv_out.bias']
							a__             =     vae_state_dict['encoder.norm_out.weight']
							a__             =     vae_state_dict['encoder.norm_out.bias']

							a__             =     vae_state_dict['decoder.conv_in.weight']
							a__             =     vae_state_dict['decoder.conv_in.bias']
							a__             =     vae_state_dict['decoder.conv_out.weight']
							a__             =     vae_state_dict['decoder.conv_out.bias']
							a__             =     vae_state_dict['decoder.norm_out.weight']
							a__             =     vae_state_dict['decoder.norm_out.bias']

							a__             =     vae_state_dict['quant_conv.weight']
							a__             =     vae_state_dict['quant_conv.bias']
							a__             =     vae_state_dict['post_quant_conv.weight']
							a__             =     vae_state_dict['post_quant_conv.bias']

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

							# Retrieves the keys for the decoder up blocks only
							a__             =     len({'.'.join(layer.split('.'   )[:3]   ) for layer in vae_state_dict if 'decoder.up' in layer}   )
							a__             =     {
							    layer_id: [key for key in vae_state_dict if F'up.{layer_id}' in key] for layer_id in range(__lowerCAmelCase   )
							}

							for i in range(__lowerCAmelCase   ):
														a__             =     [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__             =     vae_state_dict.pop(
																					    F'encoder.down.{i}.downsample.conv.weight'   )
																					a__             =     vae_state_dict.pop(
																					    F'encoder.down.{i}.downsample.conv.bias'   )

														a__             =     renew_vae_resnet_paths(__lowerCAmelCase   )
														a__             =     {'old': F'down.{i}.block', 'new': F'down_blocks.{i}.resnets'}
														assign_to_checkpoint(__lowerCAmelCase					,    __lowerCAmelCase					,    __lowerCAmelCase					,    additional_replacements=[meta_path]					,    config=__lowerCAmelCase   )

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

														a__             =     renew_vae_resnet_paths(__lowerCAmelCase   )
														a__             =     {'old': F'mid.block_{i}', 'new': F'mid_block.resnets.{i - 1}'}
														assign_to_checkpoint(__lowerCAmelCase					,    __lowerCAmelCase					,    __lowerCAmelCase					,    additional_replacements=[meta_path]					,    config=__lowerCAmelCase   )

							a__             =     [key for key in vae_state_dict if 'encoder.mid.attn' in key]
							a__             =     renew_vae_attention_paths(__lowerCAmelCase   )
							a__             =     {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'}
							assign_to_checkpoint(__lowerCAmelCase					,    __lowerCAmelCase					,    __lowerCAmelCase					,    additional_replacements=[meta_path]					,    config=__lowerCAmelCase   )
							conv_attn_to_linear(__lowerCAmelCase   )

							for i in range(__lowerCAmelCase   ):
														a__             =     num_up_blocks - 1 - i
														a__             =     [
														    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__             =     vae_state_dict[
																					    F'decoder.up.{block_id}.upsample.conv.weight'
																					]
																					a__             =     vae_state_dict[
																					    F'decoder.up.{block_id}.upsample.conv.bias'
																					]

														a__             =     renew_vae_resnet_paths(__lowerCAmelCase   )
														a__             =     {'old': F'up.{block_id}.block', 'new': F'up_blocks.{i}.resnets'}
														assign_to_checkpoint(__lowerCAmelCase					,    __lowerCAmelCase					,    __lowerCAmelCase					,    additional_replacements=[meta_path]					,    config=__lowerCAmelCase   )

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

														a__             =     renew_vae_resnet_paths(__lowerCAmelCase   )
														a__             =     {'old': F'mid.block_{i}', 'new': F'mid_block.resnets.{i - 1}'}
														assign_to_checkpoint(__lowerCAmelCase					,    __lowerCAmelCase					,    __lowerCAmelCase					,    additional_replacements=[meta_path]					,    config=__lowerCAmelCase   )

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






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

							a__             =     OmegaConf.load(__lowerCAmelCase   )
							a__             =     5_1_2
							a__             =     'cuda' if torch.cuda.is_available() else 'cpu'
							if checkpoint_path.endswith('safetensors'   ):
														from safetensors import safe_open

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

							# Convert the VAE model.
							a__             =     create_vae_diffusers_config(__lowerCAmelCase					,    image_size=__lowerCAmelCase   )
							a__             =     custom_convert_ldm_vae_checkpoint(__lowerCAmelCase					,    __lowerCAmelCase   )

							a__             =     AutoencoderKL(**__lowerCAmelCase   )
							vae.load_state_dict(__lowerCAmelCase   )
							vae.save_pretrained(__lowerCAmelCase   )


if __name__ == "__main__":
						snake_case							:       str     			=      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.''')

						snake_case							:       Union[str, Any]     			=      parser.parse_args()

						vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)








import os
import random
import sys

from . import cryptomath_module as cryptoMath  # noqa: N812
from . import rabin_miller as rabinMiller  # noqa: N812






def 							__lowercase   ( ):
							print('Making key files...'   )
							make_key_files('rsa'					,    1_0_2_4   )
							print('Key files generation successful.'   )






def 							__lowercase   ( __lowerCAmelCase							:				int   ):
							print('Generating prime p...'   )
							a__             =     rabinMiller.generate_large_prime(__lowerCAmelCase   )
							print('Generating prime q...'   )
							a__             =     rabinMiller.generate_large_prime(__lowerCAmelCase   )
							a__             =     p * q

							print('Generating e that is relatively prime to (p - 1) * (q - 1)...'   )
							while True:
														a__             =     random.randrange(2 ** (key_size - 1)					,    2 ** (key_size)   )
														if cryptoMath.gcd(__lowerCAmelCase					,    (p - 1) * (q - 1)   ) == 1:
																					break

							print('Calculating d that is mod inverse of e...'   )
							a__             =     cryptoMath.find_mod_inverse(__lowerCAmelCase					,    (p - 1) * (q - 1)   )

							a__             =     (n, e)
							a__             =     (n, d)
							return (public_key, private_key)






def 							__lowercase   ( __lowerCAmelCase							:				str					,    __lowerCAmelCase							:				int   ):
							if os.path.exists(F'{name}_pubkey.txt'   ) or os.path.exists(F'{name}_privkey.txt'   ):
														print('\nWARNING:'   )
														print(
														    F'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n'
														    'Use a different name or delete these files and re-run this program.'   )
														sys.exit()

							a__      ,					a__             =     generate_key(__lowerCAmelCase   )
							print(F'\nWriting public key to file {name}_pubkey.txt...'   )
							with open(F'{name}_pubkey.txt'					,    'w'   ) as out_file:
														out_file.write(F'{key_size},{public_key[0]},{public_key[1]}'   )

							print(F'Writing private key to file {name}_privkey.txt...'   )
							with open(F'{name}_privkey.txt'					,    'w'   ) as out_file:
														out_file.write(F'{key_size},{private_key[0]},{private_key[1]}'   )


if __name__ == "__main__":
						main()




