


'''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     (						_lowercase :     Union[str, Any]      , _lowercase :     Any  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Dict  							=      checkpoint

     __UpperCAmelCase     :			Optional[Any]  							=      {}

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

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

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

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

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

     for i in range(_lowercase  ):
          __UpperCAmelCase     :			Tuple  							=      [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:
               __UpperCAmelCase     :			Dict  							=      vae_state_dict.pop(
                   F'encoder.down.{i}.downsample.conv.weight'  )
               __UpperCAmelCase     :			Optional[Any]  							=      vae_state_dict.pop(
                   F'encoder.down.{i}.downsample.conv.bias'  )

          __UpperCAmelCase     :			Optional[int]  							=      renew_vae_resnet_paths(_lowercase  )
          __UpperCAmelCase     :			List[Any]  							=      {'''old''': F'down.{i}.block', '''new''': F'down_blocks.{i}.resnets'}
          assign_to_checkpoint(_lowercase      , _lowercase      , _lowercase      , additional_replacements=[meta_path]      , config=_lowercase  )

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

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

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

     for i in range(_lowercase  ):
          __UpperCAmelCase     :			List[str]  							=      num_up_blocks - 1 - i
          __UpperCAmelCase     :			Optional[int]  							=      [
              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:
               __UpperCAmelCase     :			Any  							=      vae_state_dict[
                   F'decoder.up.{block_id}.upsample.conv.weight'
               ]
               __UpperCAmelCase     :			Any  							=      vae_state_dict[
                   F'decoder.up.{block_id}.upsample.conv.bias'
               ]

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

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

          __UpperCAmelCase     :			Optional[int]  							=      renew_vae_resnet_paths(_lowercase  )
          __UpperCAmelCase     :			Tuple  							=      {'''old''': F'mid.block_{i}', '''new''': F'mid_block.resnets.{i - 1}'}
          assign_to_checkpoint(_lowercase      , _lowercase      , _lowercase      , additional_replacements=[meta_path]      , config=_lowercase  )

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




def      _a     (						_lowercase :     str      , _lowercase :     str      , ):





     '''simple docstring'''






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

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

          __UpperCAmelCase     :			Union[str, Any]  							=      {}
          with safe_open(_lowercase      , framework='''pt'''      , device='''cpu'''  ) as f:
               for key in f.keys():
                    __UpperCAmelCase     :			Tuple  							=      f.get_tensor(_lowercase  )
     else:
          __UpperCAmelCase     :			List[Any]  							=      torch.load(_lowercase      , map_location=_lowercase  )['''state_dict''']

     # Convert the VAE model.
     __UpperCAmelCase     :			int  							=      create_vae_diffusers_config(_lowercase      , image_size=_lowercase  )
     __UpperCAmelCase     :			str  							=      custom_convert_ldm_vae_checkpoint(_lowercase      , _lowercase  )

     __UpperCAmelCase     :			Tuple  							=      AutoencoderKL(**_lowercase  )
     vae.load_state_dict(_lowercase  )
     vae.save_pretrained(_lowercase  )


if __name__ == "__main__":
      __UpperCAmelCase      :Union[str, 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.")

      __UpperCAmelCase      :Optional[Any]			    =       parser.parse_args()

      vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)



'''simple docstring'''



from __future__ import annotations

__UpperCAmelCase      :Tuple			    =       "Muhammad Umer Farooq"
__UpperCAmelCase      :Tuple			    =       "MIT"
__UpperCAmelCase      :Union[str, Any]			    =       "1.0.0"
__UpperCAmelCase      :Optional[int]			    =       "Muhammad Umer Farooq"
__UpperCAmelCase      :Optional[Any]			    =       "contact@muhammadumerfarooq.me"
__UpperCAmelCase      :Any			    =       "Alpha"

import re
from html.parser import HTMLParser
from urllib import parse

import requests



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		Tuple							,			snake_case					:		str      )						->							None:
          super().__init__()
          __UpperCAmelCase     :			list[str]  							=      []
          __UpperCAmelCase     :			Optional[int]  							=      domain






     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		str							,			snake_case					:		list[tuple[str, str | None]]      )						->							None:
          # Only parse the 'anchor' tag.
          if tag == "a":
               # Check the list of defined attributes.
               for name, value in attrs:
                    # If href is defined, and not empty nor # print it.
                    if name == "href" and value != "#" and value != "":
                         # If not already in urls.
                         if value not in self.urls:
                              __UpperCAmelCase     :			Optional[Any]  							=      parse.urljoin(self.domain							,			snake_case      )
                              self.urls.append(snake_case      )




def      _a     (						_lowercase :     str  ):





     '''simple docstring'''






     return ".".join(get_sub_domain_name(_lowercase  ).split('''.'''  )[-2:]  )




def      _a     (						_lowercase :     str  ):





     '''simple docstring'''






     return parse.urlparse(_lowercase  ).netloc




def      _a     (						_lowercase :     str = "https://github.com"  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Union[str, Any]  							=      get_domain_name(_lowercase  )

     # Initialize the parser
     __UpperCAmelCase     :			Dict  							=      Parser(_lowercase  )

     try:
          # Open URL
          __UpperCAmelCase     :			Dict  							=      requests.get(_lowercase  )

          # pass the raw HTML to the parser to get links
          parser.feed(r.text  )

          # Get links and loop through
          __UpperCAmelCase     :			str  							=      set()
          for link in parser.urls:
               # open URL.
               # read = requests.get(link)
               try:
                    __UpperCAmelCase     :			Tuple  							=      requests.get(_lowercase  )
                    # Get the valid email.
                    __UpperCAmelCase     :			Dict  							=      re.findall('''[a-zA-Z0-9]+@''' + domain      , read.text  )
                    # If not in list then append it.
                    for email in emails:
                         valid_emails.add(_lowercase  )
               except ValueError:
                    pass
     except ValueError:
          raise SystemExit(1  )

     # Finally return a sorted list of email addresses with no duplicates.
     return sorted(_lowercase  )


if __name__ == "__main__":
      __UpperCAmelCase      :List[str]			    =       emails_from_url("https://github.com")
      print(f"""{len(emails)} emails found:""")
      print("\n".join(sorted(emails)))