





'''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__ (						lowerCAmelCase				,      lowerCAmelCase    ):





      """simple docstring"""


      _lowerCAmelCase					=				checkpoint

      _lowerCAmelCase					=				{}

      _lowerCAmelCase					=				vae_state_dict["""encoder.conv_in.weight"""]
      _lowerCAmelCase					=				vae_state_dict["""encoder.conv_in.bias"""]
      _lowerCAmelCase					=				vae_state_dict["""encoder.conv_out.weight"""]
      _lowerCAmelCase					=				vae_state_dict["""encoder.conv_out.bias"""]
      _lowerCAmelCase					=				vae_state_dict["""encoder.norm_out.weight"""]
      _lowerCAmelCase					=				vae_state_dict["""encoder.norm_out.bias"""]

      _lowerCAmelCase					=				vae_state_dict["""decoder.conv_in.weight"""]
      _lowerCAmelCase					=				vae_state_dict["""decoder.conv_in.bias"""]
      _lowerCAmelCase					=				vae_state_dict["""decoder.conv_out.weight"""]
      _lowerCAmelCase					=				vae_state_dict["""decoder.conv_out.bias"""]
      _lowerCAmelCase					=				vae_state_dict["""decoder.norm_out.weight"""]
      _lowerCAmelCase					=				vae_state_dict["""decoder.norm_out.bias"""]

      _lowerCAmelCase					=				vae_state_dict["""quant_conv.weight"""]
      _lowerCAmelCase					=				vae_state_dict["""quant_conv.bias"""]
      _lowerCAmelCase					=				vae_state_dict["""post_quant_conv.weight"""]
      _lowerCAmelCase					=				vae_state_dict["""post_quant_conv.bias"""]

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

            _lowerCAmelCase					=				renew_vae_resnet_paths(lowerCAmelCase    )
            _lowerCAmelCase					=				{"""old""": f"down.{i}.block", """new""": f"down_blocks.{i}.resnets"}
            assign_to_checkpoint(lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      additional_replacements=[meta_path]				,      config=lowerCAmelCase    )

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

            _lowerCAmelCase					=				renew_vae_resnet_paths(lowerCAmelCase    )
            _lowerCAmelCase					=				{"""old""": f"mid.block_{i}", """new""": f"mid_block.resnets.{i - 1}"}
            assign_to_checkpoint(lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      additional_replacements=[meta_path]				,      config=lowerCAmelCase    )

      _lowerCAmelCase					=				[key for key in vae_state_dict if """encoder.mid.attn""" in key]
      _lowerCAmelCase					=				renew_vae_attention_paths(lowerCAmelCase    )
      _lowerCAmelCase					=				{"""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    ):
            _lowerCAmelCase					=				num_up_blocks - 1 - i
            _lowerCAmelCase					=				[
                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:
                  _lowerCAmelCase					=				vae_state_dict[
                      f"decoder.up.{block_id}.upsample.conv.weight"
                  ]
                  _lowerCAmelCase					=				vae_state_dict[
                      f"decoder.up.{block_id}.upsample.conv.bias"
                  ]

            _lowerCAmelCase					=				renew_vae_resnet_paths(lowerCAmelCase    )
            _lowerCAmelCase					=				{"""old""": f"up.{block_id}.block", """new""": f"up_blocks.{i}.resnets"}
            assign_to_checkpoint(lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      additional_replacements=[meta_path]				,      config=lowerCAmelCase    )

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

            _lowerCAmelCase					=				renew_vae_resnet_paths(lowerCAmelCase    )
            _lowerCAmelCase					=				{"""old""": f"mid.block_{i}", """new""": f"mid_block.resnets.{i - 1}"}
            assign_to_checkpoint(lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      additional_replacements=[meta_path]				,      config=lowerCAmelCase    )

      _lowerCAmelCase					=				[key for key in vae_state_dict if """decoder.mid.attn""" in key]
      _lowerCAmelCase					=				renew_vae_attention_paths(lowerCAmelCase    )
      _lowerCAmelCase					=				{"""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   UpperCamelCase__ (						lowerCAmelCase				,      lowerCAmelCase				,      ):





      """simple docstring"""


      _lowerCAmelCase					=				requests.get(
          """ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"""    )
      _lowerCAmelCase					=				io.BytesIO(r.content    )

      _lowerCAmelCase					=				OmegaConf.load(lowerCAmelCase    )
      _lowerCAmelCase					=				5_12
      _lowerCAmelCase					=				"""cuda""" if torch.cuda.is_available() else """cpu"""
      if checkpoint_path.endswith("""safetensors"""    ):
            from safetensors import safe_open

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

      # Convert the VAE model.
      _lowerCAmelCase					=				create_vae_diffusers_config(lowerCAmelCase				,      image_size=lowerCAmelCase    )
      _lowerCAmelCase					=				custom_convert_ldm_vae_checkpoint(lowerCAmelCase				,      lowerCAmelCase    )

      _lowerCAmelCase					=				AutoencoderKL(**lowerCAmelCase    )
      vae.load_state_dict(lowerCAmelCase    )
      vae.save_pretrained(lowerCAmelCase    )


if __name__ == "__main__":
      A__							:  Tuple    =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__							:  List[str]    =parser.parse_args()

      vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)













'''simple docstring'''






import numpy as np
from cva import COLOR_BGR2GRAY, cvtColor, imread
from numpy import array, uinta
from PIL import Image

from digital_image_processing import change_contrast as cc
from digital_image_processing import convert_to_negative as cn
from digital_image_processing import sepia as sp
from digital_image_processing.dithering import burkes as bs
from digital_image_processing.edge_detection import canny
from digital_image_processing.filters import convolve as conv
from digital_image_processing.filters import gaussian_filter as gg
from digital_image_processing.filters import local_binary_pattern as lbp
from digital_image_processing.filters import median_filter as med
from digital_image_processing.filters import sobel_filter as sob
from digital_image_processing.resize import resize as rs

A__							:  List[str]    =imread(r'''digital_image_processing/image_data/lena_small.jpg''')
A__							:  Union[str, Any]    =cvtColor(img, COLOR_BGR2GRAY)
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				cn.convert_to_negative(lowerCAmelCase    )
      # assert negative_img array for at least one True
      assert negative_img.any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      with Image.open("""digital_image_processing/image_data/lena_small.jpg"""    ) as img:
            # Work around assertion for response
            assert str(cc.change_contrast(lowerCAmelCase				,      1_10    )    ).startswith(
                """<PIL.Image.Image image mode=RGB size=100x100 at"""    )
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				canny.gen_gaussian_kernel(9				,      sigma=1.4    )
      # Assert ambiguous array
      assert resp.all()
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				imread("""digital_image_processing/image_data/lena_small.jpg"""				,      0    )
      # assert ambiguous array for all == True
      assert canny_img.all()
      _lowerCAmelCase					=				canny.canny(lowerCAmelCase    )
      # assert canny array for at least one True
      assert canny_array.any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      assert gg.gaussian_filter(lowerCAmelCase				,      5				,      sigma=0.9    ).all()
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]    )
      _lowerCAmelCase					=				conv.img_convolve(lowerCAmelCase				,      lowerCAmelCase    ).astype(lowerCAmelCase    )
      assert res.any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      assert med.median_filter(lowerCAmelCase				,      3    ).any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase	,				_lowerCAmelCase					=				sob.sobel_filter(lowerCAmelCase    )
      assert grad.any() and theta.any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				sp.make_sepia(lowerCAmelCase				,      20    )
      assert sepia.all()
def   UpperCamelCase__ (						lowerCAmelCase = "digital_image_processing/image_data/lena_small.jpg"    ):





      """simple docstring"""


      _lowerCAmelCase					=				bs.Burkes(imread(lowerCAmelCase				,      1    )				,      1_20    )
      burkes.process()
      assert burkes.output_img.any()
def   UpperCamelCase__ (						lowerCAmelCase = "digital_image_processing/image_data/lena_small.jpg"				,      ):





      """simple docstring"""


      _lowerCAmelCase					=				rs.NearestNeighbour(imread(lowerCAmelCase				,      1    )				,      4_00				,      2_00    )
      nn.process()
      assert nn.output.any()





def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				"""digital_image_processing/image_data/lena.jpg"""

      # Reading the image and converting it to grayscale.
      _lowerCAmelCase					=				imread(lowerCAmelCase				,      0    )

      # Test for get_neighbors_pixel function() return not None
      _lowerCAmelCase					=				0
      _lowerCAmelCase					=				0
      _lowerCAmelCase					=				image[x_coordinate][y_coordinate]

      _lowerCAmelCase					=				lbp.get_neighbors_pixel(
          lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase    )

      assert neighbors_pixels is not None

      # Test for local_binary_pattern function()
      # Create a numpy array as the same height and width of read image
      _lowerCAmelCase					=				np.zeros((image.shape[0], image.shape[1])    )

      # Iterating through the image and calculating the local binary pattern value
      # for each pixel.
      for i in range(0				,      image.shape[0]    ):
            for j in range(0				,      image.shape[1]    ):
                  _lowerCAmelCase					=				lbp.local_binary_value(lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase    )

      assert lbp_image.any()






