



'''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  snake_case_     (					_lowerCAmelCase  :						str   ,      _lowerCAmelCase  :						Union[str, Any]  )      ->   Any:
							UpperCAmelCase :       int 							=		checkpoint

							UpperCAmelCase :       Any 							=		{}

							UpperCAmelCase :       Optional[Any] 							=		vae_state_dict['''encoder.conv_in.weight''']
							UpperCAmelCase :       Dict 							=		vae_state_dict['''encoder.conv_in.bias''']
							UpperCAmelCase :       Tuple 							=		vae_state_dict['''encoder.conv_out.weight''']
							UpperCAmelCase :       Optional[int] 							=		vae_state_dict['''encoder.conv_out.bias''']
							UpperCAmelCase :       int 							=		vae_state_dict['''encoder.norm_out.weight''']
							UpperCAmelCase :       Union[str, Any] 							=		vae_state_dict['''encoder.norm_out.bias''']

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

							UpperCAmelCase :       int 							=		vae_state_dict['''quant_conv.weight''']
							UpperCAmelCase :       Union[str, Any] 							=		vae_state_dict['''quant_conv.bias''']
							UpperCAmelCase :       Any 							=		vae_state_dict['''post_quant_conv.weight''']
							UpperCAmelCase :       List[Any] 							=		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 :       Optional[Any] 							=		{
							    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
							UpperCAmelCase :       Any 							=		len({'''.'''.join(layer.split('''.'''  )[:3]  ) for layer in vae_state_dict if '''decoder.up''' in layer}  )
							UpperCAmelCase :       List[str] 							=		{
							    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  ):
														UpperCAmelCase :       Dict 							=		[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 :       Optional[int] 							=		vae_state_dict.pop(
																					    f"""encoder.down.{i}.downsample.conv.weight"""  )
																					UpperCAmelCase :       List[Any] 							=		vae_state_dict.pop(
																					    f"""encoder.down.{i}.downsample.conv.bias"""  )

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

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

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

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

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

							UpperCAmelCase :       Dict 							=		[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 :       List[str] 							=		[key for key in mid_resnets if f"""decoder.mid.block_{i}""" in key]

														UpperCAmelCase :       List[str] 							=		renew_vae_resnet_paths(_lowerCAmelCase  )
														UpperCAmelCase :       Optional[int] 							=		{'''old''': f"""mid.block_{i}""", '''new''': f"""mid_block.resnets.{i - 1}"""}
														assign_to_checkpoint(_lowerCAmelCase   ,      _lowerCAmelCase   ,      _lowerCAmelCase   ,      additional_replacements=[meta_path]   ,      config=_lowerCAmelCase  )

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

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

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

							# Convert the VAE model.
							UpperCAmelCase :       List[Any] 							=		create_vae_diffusers_config(_lowerCAmelCase   ,      image_size=_lowerCAmelCase  )
							UpperCAmelCase :       Tuple 							=		custom_convert_ldm_vae_checkpoint(_lowerCAmelCase   ,      _lowerCAmelCase  )

							UpperCAmelCase :       Tuple 							=		AutoencoderKL(**_lowerCAmelCase  )
							vae.load_state_dict(_lowerCAmelCase  )
							vae.save_pretrained(_lowerCAmelCase  )


if __name__ == "__main__":
						UpperCamelCase__:   Dict								=			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__:   str								=			parser.parse_args()

						vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)










'''simple docstring'''






import warnings
from contextlib import contextmanager

from ....processing_utils import ProcessorMixin

class 				SCREAMING_SNAKE_CASE(							A__			):







	"""simple docstring"""






	lowerCamelCase__			 =       """MCTCTFeatureExtractor"""
	lowerCamelCase__			 =       """AutoTokenizer"""







	def __init__(						self			:     Dict		,			__snake_case			:     Optional[int]		,			__snake_case			:     List[str]		)			->		str:
								super().__init__(__snake_case		,			__snake_case		)
								UpperCAmelCase :       List[Any] 							=		self.feature_extractor
								UpperCAmelCase :       Union[str, Any] 							=		False







	def __call__(						self			:     Any		,			*__snake_case			:     List[str]		,			**__snake_case			:     Any		)			->		List[Any]:
								# For backward compatibility
								if self._in_target_context_manager:
															return self.current_processor(*__snake_case		,			**__snake_case		)

								if "raw_speech" in kwargs:
															warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'''		)
															UpperCAmelCase :       int 							=		kwargs.pop('''raw_speech'''		)
								else:
															UpperCAmelCase :       Union[str, Any] 							=		kwargs.pop('''audio'''		,			__snake_case		)
								UpperCAmelCase :       Optional[Any] 							=		kwargs.pop('''sampling_rate'''		,			__snake_case		)
								UpperCAmelCase :       Dict 							=		kwargs.pop('''text'''		,			__snake_case		)
								if len(__snake_case		) > 0:
															UpperCAmelCase :       Any 							=		args[0]
															UpperCAmelCase :       Optional[int] 							=		args[1:]

								if audio is None and text is None:
															raise ValueError('''You need to specify either an `audio` or `text` input to process.'''		)

								if audio is not None:
															UpperCAmelCase :       List[str] 							=		self.feature_extractor(__snake_case		,			*__snake_case		,			sampling_rate=__snake_case		,			**__snake_case		)
								if text is not None:
															UpperCAmelCase :       int 							=		self.tokenizer(__snake_case		,			**__snake_case		)

								if text is None:
															return inputs
								elif audio is None:
															return encodings
								else:
															UpperCAmelCase :       str 							=		encodings['''input_ids''']
															return inputs







	def      A	(						self			:     List[Any]		,			*__snake_case			:     List[Any]		,			**__snake_case			:     List[Any]		)			->		str:
								return self.tokenizer.batch_decode(*__snake_case		,			**__snake_case		)







	def      A	(						self			:     List[Any]		,			*__snake_case			:     int		,			**__snake_case			:     Optional[int]		)			->		Any:
								# For backward compatibility
								if self._in_target_context_manager:
															return self.current_processor.pad(*__snake_case		,			**__snake_case		)

								UpperCAmelCase :       List[Any] 							=		kwargs.pop('''input_features'''		,			__snake_case		)
								UpperCAmelCase :       Optional[Any] 							=		kwargs.pop('''labels'''		,			__snake_case		)
								if len(__snake_case		) > 0:
															UpperCAmelCase :       List[str] 							=		args[0]
															UpperCAmelCase :       List[Any] 							=		args[1:]

								if input_features is not None:
															UpperCAmelCase :       Tuple 							=		self.feature_extractor.pad(__snake_case		,			*__snake_case		,			**__snake_case		)
								if labels is not None:
															UpperCAmelCase :       Optional[int] 							=		self.tokenizer.pad(__snake_case		,			**__snake_case		)

								if labels is None:
															return input_features
								elif input_features is None:
															return labels
								else:
															UpperCAmelCase :       List[str] 							=		labels['''input_ids''']
															return input_features







	def      A	(						self			:     Union[str, Any]		,			*__snake_case			:     Optional[Any]		,			**__snake_case			:     Optional[int]		)			->		Optional[Any]:
								return self.tokenizer.decode(*__snake_case		,			**__snake_case		)







	@contextmanager
	def      A	(						self			:     Any		)			->		Optional[int]:
								warnings.warn(
								    '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
								    '''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
								    '''your audio inputs, or in a separate call.'''		)
								UpperCAmelCase :       Dict 							=		True
								UpperCAmelCase :       List[Any] 							=		self.tokenizer
								yield
								UpperCAmelCase :       Tuple 							=		self.feature_extractor
								UpperCAmelCase :       List[Any] 							=		False





