



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						(      _UpperCAmelCase							:					Any ,   _UpperCAmelCase							:					List[Any]						):







		'''simple docstring'''





		__UpperCAmelCase    :     str													=	checkpoint

		__UpperCAmelCase    :     Union[str, Any]													=	{}

		__UpperCAmelCase    :     Any													=	vae_state_dict["encoder.conv_in.weight"]
		__UpperCAmelCase    :     Tuple													=	vae_state_dict["encoder.conv_in.bias"]
		__UpperCAmelCase    :     Dict													=	vae_state_dict["encoder.conv_out.weight"]
		__UpperCAmelCase    :     Optional[Any]													=	vae_state_dict["encoder.conv_out.bias"]
		__UpperCAmelCase    :     Any													=	vae_state_dict["encoder.norm_out.weight"]
		__UpperCAmelCase    :     Dict													=	vae_state_dict["encoder.norm_out.bias"]

		__UpperCAmelCase    :     Tuple													=	vae_state_dict["decoder.conv_in.weight"]
		__UpperCAmelCase    :     Union[str, Any]													=	vae_state_dict["decoder.conv_in.bias"]
		__UpperCAmelCase    :     int													=	vae_state_dict["decoder.conv_out.weight"]
		__UpperCAmelCase    :     Optional[int]													=	vae_state_dict["decoder.conv_out.bias"]
		__UpperCAmelCase    :     Any													=	vae_state_dict["decoder.norm_out.weight"]
		__UpperCAmelCase    :     Optional[int]													=	vae_state_dict["decoder.norm_out.bias"]

		__UpperCAmelCase    :     List[Any]													=	vae_state_dict["quant_conv.weight"]
		__UpperCAmelCase    :     int													=	vae_state_dict["quant_conv.bias"]
		__UpperCAmelCase    :     List[Any]													=	vae_state_dict["post_quant_conv.weight"]
		__UpperCAmelCase    :     Optional[int]													=	vae_state_dict["post_quant_conv.bias"]

		# Retrieves the keys for the encoder down blocks only
		__UpperCAmelCase    :     int													=	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(_UpperCAmelCase						)
		}

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

				__UpperCAmelCase    :     Dict													=	renew_vae_resnet_paths(_UpperCAmelCase						)
				__UpperCAmelCase    :     str													=	{"old": f'down.{i}.block', "new": f'down_blocks.{i}.resnets'}
				assign_to_checkpoint(_UpperCAmelCase ,   _UpperCAmelCase ,   _UpperCAmelCase ,   additional_replacements=[meta_path] ,   config=_UpperCAmelCase						)

		__UpperCAmelCase    :     Optional[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    :     Any													=	[key for key in mid_resnets if f'encoder.mid.block_{i}' in key]

				__UpperCAmelCase    :     List[Any]													=	renew_vae_resnet_paths(_UpperCAmelCase						)
				__UpperCAmelCase    :     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						)

		__UpperCAmelCase    :     List[Any]													=	[key for key in vae_state_dict if "encoder.mid.attn" in key]
		__UpperCAmelCase    :     List[str]													=	renew_vae_attention_paths(_UpperCAmelCase						)
		__UpperCAmelCase    :     Optional[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						):
				__UpperCAmelCase    :     Union[str, Any]													=	num_up_blocks - 1 - i
				__UpperCAmelCase    :     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:
						__UpperCAmelCase    :     Dict													=	vae_state_dict[
						    f'decoder.up.{block_id}.upsample.conv.weight'
						]
						__UpperCAmelCase    :     Optional[Any]													=	vae_state_dict[
						    f'decoder.up.{block_id}.upsample.conv.bias'
						]

				__UpperCAmelCase    :     Optional[Any]													=	renew_vae_resnet_paths(_UpperCAmelCase						)
				__UpperCAmelCase    :     List[str]													=	{"old": f'up.{block_id}.block', "new": f'up_blocks.{i}.resnets'}
				assign_to_checkpoint(_UpperCAmelCase ,   _UpperCAmelCase ,   _UpperCAmelCase ,   additional_replacements=[meta_path] ,   config=_UpperCAmelCase						)

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

				__UpperCAmelCase    :     Any													=	renew_vae_resnet_paths(_UpperCAmelCase						)
				__UpperCAmelCase    :     Optional[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						)

		__UpperCAmelCase    :     Tuple													=	[key for key in vae_state_dict if "decoder.mid.attn" in key]
		__UpperCAmelCase    :     Any													=	renew_vae_attention_paths(_UpperCAmelCase						)
		__UpperCAmelCase    :     Optional[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						)
		return new_checkpoint

def        a						(      _UpperCAmelCase							:					Union[str, Any] ,   _UpperCAmelCase							:					int ,   ):







		'''simple docstring'''





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

		__UpperCAmelCase    :     Any													=	OmegaConf.load(_UpperCAmelCase						)
		__UpperCAmelCase    :     Optional[Any]													=	5_12
		__UpperCAmelCase    :     Tuple													=	"cuda" if torch.cuda.is_available() else "cpu"
		if checkpoint_path.endswith('''safetensors'''						):
				from safetensors import safe_open

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

		# Convert the VAE model.
		__UpperCAmelCase    :     Optional[int]													=	create_vae_diffusers_config(_UpperCAmelCase ,   image_size=_UpperCAmelCase						)
		__UpperCAmelCase    :     Optional[int]													=	custom_convert_ldm_vae_checkpoint(_UpperCAmelCase ,   _UpperCAmelCase						)

		__UpperCAmelCase    :     int													=	AutoencoderKL(**_UpperCAmelCase						)
		vae.load_state_dict(_UpperCAmelCase						)
		vae.save_pretrained(_UpperCAmelCase						)


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)








import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import Audio, Features, Value
from .base import TaskTemplate



@dataclass(frozen=UpperCAmelCase_	)
class   __lowercase				( UpperCAmelCase_	):




			"""simple docstring"""







			_UpperCAmelCase   :							str										=     field(default='''automatic-speech-recognition'''		,       metadata={'''include_in_asdict_even_if_is_default''': True}	)
			_UpperCAmelCase   :							ClassVar[Features]										=     Features({'''audio''': Audio()}	)
			_UpperCAmelCase   :							ClassVar[Features]										=     Features({'''transcription''': Value('''string'''	)}	)
			_UpperCAmelCase   :							str										=     "audio"
			_UpperCAmelCase   :							str										=     "transcription"



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]   ,						lowerCAmelCase__  :     int):
									if self.audio_column not in features:
															raise ValueError(F"Column {self.audio_column} is not present in features.")
									if not isinstance(features[self.audio_column]   ,						lowerCAmelCase__):
															raise ValueError(F"Column {self.audio_column} is not an Audio type.")
									SCREAMING_SNAKE_CASE_: Tuple  		=       copy.deepcopy(self)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       self.input_schema.copy()
									SCREAMING_SNAKE_CASE_: Dict  		=       features[self.audio_column]
									SCREAMING_SNAKE_CASE_: int  		=       input_schema
									return task_template




			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									return {self.audio_column: "audio", self.transcription_column: "transcription"}






