
"""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				(		snake_case__   :     Optional[int]	,      snake_case__   :     List[Any]     ):
	A						   =   checkpoint

	A						   =   {}

	A						   =   vae_state_dict['encoder.conv_in.weight']
	A						   =   vae_state_dict['encoder.conv_in.bias']
	A						   =   vae_state_dict['encoder.conv_out.weight']
	A						   =   vae_state_dict['encoder.conv_out.bias']
	A						   =   vae_state_dict['encoder.norm_out.weight']
	A						   =   vae_state_dict['encoder.norm_out.bias']

	A						   =   vae_state_dict['decoder.conv_in.weight']
	A						   =   vae_state_dict['decoder.conv_in.bias']
	A						   =   vae_state_dict['decoder.conv_out.weight']
	A						   =   vae_state_dict['decoder.conv_out.bias']
	A						   =   vae_state_dict['decoder.norm_out.weight']
	A						   =   vae_state_dict['decoder.norm_out.bias']

	A						   =   vae_state_dict['quant_conv.weight']
	A						   =   vae_state_dict['quant_conv.bias']
	A						   =   vae_state_dict['post_quant_conv.weight']
	A						   =   vae_state_dict['post_quant_conv.bias']

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

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

	for i in range(snake_case__     ):
		A						   =   [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:
			A						   =   vae_state_dict.pop(
			    F'encoder.down.{i}.downsample.conv.weight'     )
			A						   =   vae_state_dict.pop(
			    F'encoder.down.{i}.downsample.conv.bias'     )

		A						   =   renew_vae_resnet_paths(snake_case__     )
		A						   =   {'old': F'down.{i}.block', 'new': F'down_blocks.{i}.resnets'}
		assign_to_checkpoint(snake_case__	,      snake_case__	,      snake_case__	,      additional_replacements=[meta_path]	,      config=snake_case__     )

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

		A						   =   renew_vae_resnet_paths(snake_case__     )
		A						   =   {'old': F'mid.block_{i}', 'new': F'mid_block.resnets.{i - 1}'}
		assign_to_checkpoint(snake_case__	,      snake_case__	,      snake_case__	,      additional_replacements=[meta_path]	,      config=snake_case__     )

	A						   =   [key for key in vae_state_dict if 'encoder.mid.attn' in key]
	A						   =   renew_vae_attention_paths(snake_case__     )
	A						   =   {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'}
	assign_to_checkpoint(snake_case__	,      snake_case__	,      snake_case__	,      additional_replacements=[meta_path]	,      config=snake_case__     )
	conv_attn_to_linear(snake_case__     )

	for i in range(snake_case__     ):
		A						   =   num_up_blocks - 1 - i
		A						   =   [
		    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:
			A						   =   vae_state_dict[
			    F'decoder.up.{block_id}.upsample.conv.weight'
			]
			A						   =   vae_state_dict[
			    F'decoder.up.{block_id}.upsample.conv.bias'
			]

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

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

		A						   =   renew_vae_resnet_paths(snake_case__     )
		A						   =   {'old': F'mid.block_{i}', 'new': F'mid_block.resnets.{i - 1}'}
		assign_to_checkpoint(snake_case__	,      snake_case__	,      snake_case__	,      additional_replacements=[meta_path]	,      config=snake_case__     )

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






def       _snake_case				(		snake_case__   :     str	,      snake_case__   :     str	,      ):
	# Only support V1
	A						   =   requests.get(
	    ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'     )
	A						   =   io.BytesIO(r.content     )

	A						   =   OmegaConf.load(snake_case__     )
	A						   =   512
	A						   =   'cuda' if torch.cuda.is_available() else 'cpu'
	if checkpoint_path.endswith('safetensors'     ):
		from safetensors import safe_open

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

	# Convert the VAE model.
	A						   =   create_vae_diffusers_config(snake_case__	,      image_size=snake_case__     )
	A						   =   custom_convert_ldm_vae_checkpoint(snake_case__	,      snake_case__     )

	A						   =   AutoencoderKL(**snake_case__     )
	vae.load_state_dict(snake_case__     )
	vae.save_pretrained(snake_case__     )


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)

"""simple docstring"""


import argparse
import os
import pickle
import sys

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
_lowercase							   =				data_utils.TransfoXLTokenizer
_lowercase							   =				data_utils.TransfoXLCorpus
_lowercase							   =				data_utils
_lowercase							   =				data_utils






def       _snake_case				(		snake_case__   :     Union[str, Any]	,      snake_case__   :     Dict	,      snake_case__   :     Tuple	,      snake_case__   :     int     ):
	if transfo_xl_dataset_file:
		# Convert a pre-processed corpus (see original TensorFlow repo)
		with open(snake_case__	,      'rb'     ) as fp:
			A						   =   pickle.load(snake_case__	,      encoding='latin1'     )
		# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
		A						   =   pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file']
		print(F'Save vocabulary to {pytorch_vocab_dump_path}'     )
		A						   =   corpus.vocab.__dict__
		torch.save(snake_case__	,      snake_case__     )

		A						   =   corpus.__dict__
		corpus_dict_no_vocab.pop('vocab'	,      snake_case__     )
		A						   =   pytorch_dump_folder_path + '/' + CORPUS_NAME
		print(F'Save dataset to {pytorch_dataset_dump_path}'     )
		torch.save(snake_case__	,      snake_case__     )

	if tf_checkpoint_path:
		# Convert a pre-trained TensorFlow model
		A						   =   os.path.abspath(snake_case__     )
		A						   =   os.path.abspath(snake_case__     )

		print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.'     )
		# Initialise PyTorch model
		if transfo_xl_config_file == "":
			A						   =   TransfoXLConfig()
		else:
			A						   =   TransfoXLConfig.from_json_file(snake_case__     )
		print(F'Building PyTorch model from configuration: {config}'     )
		A						   =   TransfoXLLMHeadModel(snake_case__     )

		A						   =   load_tf_weights_in_transfo_xl(snake_case__	,      snake_case__	,      snake_case__     )
		# Save pytorch-model
		A						   =   os.path.join(snake_case__	,      snake_case__     )
		A						   =   os.path.join(snake_case__	,      snake_case__     )
		print(F'Save PyTorch model to {os.path.abspath(snake_case__     )}'     )
		torch.save(model.state_dict()	,      snake_case__     )
		print(F'Save configuration file to {os.path.abspath(snake_case__     )}'     )
		with open(snake_case__	,      'w'	,      encoding='utf-8'     ) as f:
			f.write(config.to_json_string()     )


if __name__ == "__main__":
		_lowercase							   =				argparse.ArgumentParser()
		parser.add_argument(
		    '''--pytorch_dump_folder_path''',
		    default=None,
		    type=str,
		    required=True,
		    help='''Path to the folder to store the PyTorch model or dataset/vocab.''',
		)
		parser.add_argument(
		    '''--tf_checkpoint_path''',
		    default='''''',
		    type=str,
		    help='''An optional path to a TensorFlow checkpoint path to be converted.''',
		)
		parser.add_argument(
		    '''--transfo_xl_config_file''',
		    default='''''',
		    type=str,
		    help=(
		        '''An optional config json file corresponding to the pre-trained BERT model. \n'''
		        '''This specifies the model architecture.'''
		    ),
		)
		parser.add_argument(
		    '''--transfo_xl_dataset_file''',
		    default='''''',
		    type=str,
		    help='''An optional dataset file to be converted in a vocabulary.''',
		)
		_lowercase							   =				parser.parse_args()
		convert_transfo_xl_checkpoint_to_pytorch(
		    args.tf_checkpoint_path,
		    args.transfo_xl_config_file,
		    args.pytorch_dump_folder_path,
		    args.transfo_xl_dataset_file,
		)