'''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 _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       Optional[Any]     				=					checkpoint

     lowercase_					:       List[str]     				=					{}

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

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

     lowercase_					:       Any     				=					vae_state_dict['quant_conv.weight']
     lowercase_					:       Any     				=					vae_state_dict['quant_conv.bias']
     lowercase_					:       Optional[Any]     				=					vae_state_dict['post_quant_conv.weight']
     lowercase_					:       Dict     				=					vae_state_dict['post_quant_conv.bias']

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

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

     for i in range(SCREAMING_SNAKE_CASE_							):
          lowercase_					:       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:
               lowercase_					:       Union[str, Any]     				=					vae_state_dict.pop(
                   f'''encoder.down.{i}.downsample.conv.weight'''							)
               lowercase_					:       Optional[Any]     				=					vae_state_dict.pop(
                   f'''encoder.down.{i}.downsample.conv.bias'''							)

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

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

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

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

     for i in range(SCREAMING_SNAKE_CASE_							):
          lowercase_					:       Dict     				=					num_up_blocks - 1 - i
          lowercase_					:       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:
               lowercase_					:       Dict     				=					vae_state_dict[
                   f'''decoder.up.{block_id}.upsample.conv.weight'''
               ]
               lowercase_					:       Optional[Any]     				=					vae_state_dict[
                   f'''decoder.up.{block_id}.upsample.conv.bias'''
               ]

          lowercase_					:       Optional[int]     				=					renew_vae_resnet_paths(SCREAMING_SNAKE_CASE_							)
          lowercase_					:       str     				=					{'old': f'''up.{block_id}.block''', 'new': f'''up_blocks.{i}.resnets'''}
          assign_to_checkpoint(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       additional_replacements=[meta_path]  ,       config=SCREAMING_SNAKE_CASE_							)

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

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

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

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       ):
     # Only support V1
     lowercase_					:       List[str]     				=					requests.get(
         ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'							)
     lowercase_					:       Any     				=					io.BytesIO(r.content							)

     lowercase_					:       Any     				=					OmegaConf.load(SCREAMING_SNAKE_CASE_							)
     lowercase_					:       str     				=					512
     lowercase_					:       Optional[int]     				=					'cuda' if torch.cuda.is_available() else 'cpu'
     if checkpoint_path.endswith('safetensors'							):
          from safetensors import safe_open

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

     # Convert the VAE model.
     lowercase_					:       List[str]     				=					create_vae_diffusers_config(SCREAMING_SNAKE_CASE_  ,       image_size=SCREAMING_SNAKE_CASE_							)
     lowercase_					:       Dict     				=					custom_convert_ldm_vae_checkpoint(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							)

     lowercase_					:       Any     				=					AutoencoderKL(**SCREAMING_SNAKE_CASE_							)
     vae.load_state_dict(SCREAMING_SNAKE_CASE_							)
     vae.save_pretrained(SCREAMING_SNAKE_CASE_							)


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

 _A								=   parser.parse_args()

 vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)





'''simple docstring'''




from decimal import Decimal, getcontext
from math import ceil, factorial

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):

     if not isinstance(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
          raise TypeError('Undefined for non-integers'							)
     elif precision < 1:
          raise ValueError('Undefined for non-natural numbers'							)

     lowercase_					:       str     				=					precision
     lowercase_					:       List[str]     				=					ceil(precision / 14							)
     lowercase_					:       Union[str, Any]     				=					426_880 * Decimal(10_005							).sqrt()
     lowercase_					:       List[Any]     				=					1
     lowercase_					:       Optional[int]     				=					13_591_409
     lowercase_					:       Dict     				=					Decimal(SCREAMING_SNAKE_CASE_							)
     for k in range(1  ,       SCREAMING_SNAKE_CASE_							):
          lowercase_					:       List[str]     				=					factorial(6 * k							) // (factorial(3 * k							) * factorial(SCREAMING_SNAKE_CASE_							) ** 3)
          linear_term += 545_140_134
          exponential_term *= -262_537_412_640_768_000
          partial_sum += Decimal(multinomial_term * linear_term							) / exponential_term
     return str(constant_term / partial_sum							)[:-1]


if __name__ == "__main__":
 _A								=   5_0
 print(F"""The first {n} digits of pi is: {pi(n)}""")




