
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 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     Any			,							UpperCAmelCase_	:     Optional[Any]				)			->						List[Any]:
       SCREAMING_SNAKE_CASE_							:				List[Any]		=checkpoint

       SCREAMING_SNAKE_CASE_							:				Union[str, Any]		={}

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

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

       SCREAMING_SNAKE_CASE_							:				Optional[int]		=vae_state_dict['''quant_conv.weight''']
       SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=vae_state_dict['''quant_conv.bias''']
       SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=vae_state_dict['''post_quant_conv.weight''']
       SCREAMING_SNAKE_CASE_							:				Dict		=vae_state_dict['''post_quant_conv.bias''']

       # Retrieves the keys for the encoder down blocks only
       SCREAMING_SNAKE_CASE_							:				Dict		=len({'''.'''.join(layer.split('''.'''				)[:3]				) for layer in vae_state_dict if '''encoder.down''' in layer}				)
       SCREAMING_SNAKE_CASE_							:				Dict		={
           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
       SCREAMING_SNAKE_CASE_							:				Optional[Any]		=len({'''.'''.join(layer.split('''.'''				)[:3]				) for layer in vae_state_dict if '''decoder.up''' in layer}				)
       SCREAMING_SNAKE_CASE_							:				Dict		={
           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_				):
              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_							:				Dict		=vae_state_dict.pop(
                         f'encoder.down.{i}.downsample.conv.weight'				)
                     SCREAMING_SNAKE_CASE_							:				Optional[Any]		=vae_state_dict.pop(
                         f'encoder.down.{i}.downsample.conv.bias'				)

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

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

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

       SCREAMING_SNAKE_CASE_							:				Optional[Any]		=[key for key in vae_state_dict if '''encoder.mid.attn''' in key]
       SCREAMING_SNAKE_CASE_							:				str		=renew_vae_attention_paths(UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				List[Any]		={'''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_				):
              SCREAMING_SNAKE_CASE_							:				Dict		=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_							:				Dict		=vae_state_dict[
                         f'decoder.up.{block_id}.upsample.conv.weight'
                     ]
                     SCREAMING_SNAKE_CASE_							:				str		=vae_state_dict[
                         f'decoder.up.{block_id}.upsample.conv.bias'
                     ]

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

       SCREAMING_SNAKE_CASE_							:				str		=[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_							:				Union[str, Any]		=[key for key in mid_resnets if f'decoder.mid.block_{i}' in key]

              SCREAMING_SNAKE_CASE_							:				int		=renew_vae_resnet_paths(UpperCAmelCase_				)
              SCREAMING_SNAKE_CASE_							:				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_				)

       SCREAMING_SNAKE_CASE_							:				Optional[int]		=[key for key in vae_state_dict if '''decoder.mid.attn''' in key]
       SCREAMING_SNAKE_CASE_							:				str		=renew_vae_attention_paths(UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				Dict		={'''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 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     str			,							UpperCAmelCase_	:     str			,							)			->						Dict:
       # Only support V1
       SCREAMING_SNAKE_CASE_							:				int		=requests.get(
           ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'''				)
       SCREAMING_SNAKE_CASE_							:				Tuple		=io.BytesIO(r.content				)

       SCREAMING_SNAKE_CASE_							:				Optional[Any]		=OmegaConf.load(UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				Any		=5_1_2
       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_							:				List[str]		={}
              with safe_open(UpperCAmelCase_			,							framework='''pt'''			,							device='''cpu'''				) as f:
                     for key in f.keys():
                            SCREAMING_SNAKE_CASE_							:				Dict		=f.get_tensor(UpperCAmelCase_				)
       else:
              SCREAMING_SNAKE_CASE_							:				List[str]		=torch.load(UpperCAmelCase_			,							map_location=UpperCAmelCase_				)['''state_dict''']

       # Convert the VAE model.
       SCREAMING_SNAKE_CASE_							:				Dict		=create_vae_diffusers_config(UpperCAmelCase_			,							image_size=UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				str		=custom_convert_ldm_vae_checkpoint(UpperCAmelCase_			,							UpperCAmelCase_				)

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


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

 _lowercase											=    parser.parse_args()

 vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)


from math import isqrt, loga
def 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     int				)			->						list[int]:
       SCREAMING_SNAKE_CASE_							:				int		=[True] * max_number
       for i in range(2			,							isqrt(max_number - 1				) + 1				):
              if is_prime[i]:
                     for j in range(i**2			,							UpperCAmelCase_			,							UpperCAmelCase_				):
                            SCREAMING_SNAKE_CASE_							:				Dict		=False

       return [i for i in range(2			,							UpperCAmelCase_				) if is_prime[i]]
def 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     int = 8_0_0_8_0_0			,							UpperCAmelCase_	:     int = 8_0_0_8_0_0				)			->						int:
       SCREAMING_SNAKE_CASE_							:				str		=degree * loga(UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				List[Any]		=int(UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				int		=calculate_prime_numbers(UpperCAmelCase_				)

       SCREAMING_SNAKE_CASE_							:				int		=0
       SCREAMING_SNAKE_CASE_							:				List[Any]		=0
       SCREAMING_SNAKE_CASE_							:				Any		=len(UpperCAmelCase_				) - 1
       while left < right:
              while (
                  prime_numbers[right] * loga(prime_numbers[left]				)
                  + prime_numbers[left] * loga(prime_numbers[right]				)
                  > upper_bound
              ):
                     right -= 1
              hybrid_integers_count += right - left
              left += 1

       return hybrid_integers_count


if __name__ == "__main__":
 print(F"{solution() = }")
