


"""simple docstring"""




import argparse
import re
from typing import Dict

import torch
from datasets import Audio, Dataset, load_dataset, load_metric

from transformers import AutoFeatureExtractor, pipeline

def        lowercase							(		lowerCAmelCase__ :     Dataset    ,					lowerCAmelCase__ :     Dict[str, str]			) ->      Dict:
		__a           =			args.log_outputs
		__a           =			'''_'''.join(args.dataset.split('''/'''			) + [args.config, args.split]			)

		# load metric
		__a           =			load_metric('''wer'''			)
		__a           =			load_metric('''cer'''			)

		# compute metrics
		__a           =			wer.compute(references=result['''target''']    ,					predictions=result['''prediction''']			)
		__a           =			cer.compute(references=result['''target''']    ,					predictions=result['''prediction''']			)

		# print & log results
		__a           =			f'''WER: {wer_result}\nCER: {cer_result}'''
		print(lowerCAmelCase__			)

		with open(f'''{dataset_id}_eval_results.txt'''    ,					'''w'''			) as f:
				f.write(lowerCAmelCase__			)

		# log all results in text file. Possibly interesting for analysis
		if log_outputs is not None:
				__a           =			f'''log_{dataset_id}_predictions.txt'''
				__a           =			f'''log_{dataset_id}_targets.txt'''

				with open(lowerCAmelCase__    ,					'''w'''			) as p, open(lowerCAmelCase__    ,					'''w'''			) as t:
						# mapping function to write output
						def write_to_file(lowerCAmelCase__ :     List[Any]    ,					lowerCAmelCase__ :     int			):
								p.write(f'''{i}''' + '''\n'''			)
								p.write(batch['''prediction'''] + '''\n'''			)
								t.write(f'''{i}''' + '''\n'''			)
								t.write(batch['''target'''] + '''\n'''			)

						result.map(lowerCAmelCase__    ,					with_indices=lowerCAmelCase__			)

def        lowercase							(		lowerCAmelCase__ :     str			) ->      str:
		__a           =			'''[,?.!\-\;\:"“%‘”�—’…–]'''  # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training

		__a           =			re.sub(lowerCAmelCase__    ,					''''''    ,					text.lower()			)

		# In addition, we can normalize the target text, e.g. removing new lines characters etc...
		# note that order is important here!
		__a           =			['''\n\n''', '''\n''', '''   ''', '''  ''']

		for t in token_sequences_to_ignore:
				__a           =			''' '''.join(text.split(lowerCAmelCase__			)			)

		return text

def        lowercase							(		lowerCAmelCase__ :     int			) ->      Any:
		# load dataset
		__a           =			load_dataset(args.dataset    ,					args.config    ,					split=args.split    ,					use_auth_token=lowerCAmelCase__			)

		# for testing: only process the first two examples as a test
		# dataset = dataset.select(range(10))

		# load processor
		__a           =			AutoFeatureExtractor.from_pretrained(args.model_id			)
		__a           =			feature_extractor.sampling_rate

		# resample audio
		__a           =			dataset.cast_column('''audio'''    ,					Audio(sampling_rate=lowerCAmelCase__			)			)

		# load eval pipeline
		if args.device is None:
				__a           =			0 if torch.cuda.is_available() else -1
		__a           =			pipeline('''automatic-speech-recognition'''    ,					model=args.model_id    ,					device=args.device			)

		# map function to decode audio
		def map_to_pred(lowerCAmelCase__ :     Any			):
				__a           =			asr(
				    batch['''audio''']['''array''']    ,					chunk_length_s=args.chunk_length_s    ,					stride_length_s=args.stride_length_s			)

				__a           =			prediction['''text''']
				__a           =			normalize_text(batch['''sentence''']			)
				return batch

		# run inference on all examples
		__a           =			dataset.map(lowerCAmelCase__    ,					remove_columns=dataset.column_names			)

		# compute and log_results
		# do not change function below
		log_results(lowerCAmelCase__    ,					lowerCAmelCase__			)


if __name__ == "__main__":
				lowercase_			     =  argparse.ArgumentParser()

				parser.add_argument(
				    "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
				)
				parser.add_argument(
				    "--dataset",
				    type=str,
				    required=True,
				    help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
				)
				parser.add_argument(
				    "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'`  for Common Voice"
				)
				parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
				parser.add_argument(
				    "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
				)
				parser.add_argument(
				    "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
				)
				parser.add_argument(
				    "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
				)
				parser.add_argument(
				    "--device",
				    type=int,
				    default=None,
				    help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
				)
				lowercase_			     =  parser.parse_args()

				main(args)














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 				lowerCamelCase__      (    __lowerCamelCase			:     Dict  ,		__lowerCamelCase			:     int		):
  __UpperCAmelCase							:	List[Any]           =  checkpoint

  __UpperCAmelCase							:	Tuple           =  {}

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

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

  __UpperCAmelCase							:	Optional[int]           =  vae_state_dict["""quant_conv.weight"""]
  __UpperCAmelCase							:	int           =  vae_state_dict["""quant_conv.bias"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""post_quant_conv.weight"""]
  __UpperCAmelCase							:	Any           =  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							:	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							:	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(__lowerCamelCase		)
  }

  for i in range(__lowerCamelCase		):
    __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							:	Optional[Any]           =  vae_state_dict.pop(
          f"""encoder.down.{i}.downsample.conv.weight"""		)
      __UpperCAmelCase							:	int           =  vae_state_dict.pop(
          f"""encoder.down.{i}.downsample.conv.bias"""		)

    __UpperCAmelCase							:	Optional[int]           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Optional[Any]           =  {"""old""": f"""down.{i}.block""", """new""": f"""down_blocks.{i}.resnets"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

  __UpperCAmelCase							:	Tuple           =  [key for key in vae_state_dict if """encoder.mid.block""" in key]
  __UpperCAmelCase							:	Optional[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							:	Tuple           =  {"""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							:	List[Any]           =  [key for key in vae_state_dict if """encoder.mid.attn""" in key]
  __UpperCAmelCase							:	str           =  renew_vae_attention_paths(__lowerCamelCase		)
  __UpperCAmelCase							:	List[str]           =  {"""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							:	Optional[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							:	int           =  vae_state_dict[
          f"""decoder.up.{block_id}.upsample.conv.weight"""
      ]
      __UpperCAmelCase							:	Dict           =  vae_state_dict[
          f"""decoder.up.{block_id}.upsample.conv.bias"""
      ]

    __UpperCAmelCase							:	Dict           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Optional[Any]           =  {"""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							:	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							:	Dict           =  [key for key in mid_resnets if f"""decoder.mid.block_{i}""" in key]

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

  __UpperCAmelCase							:	Dict           =  OmegaConf.load(__lowerCamelCase		)
  __UpperCAmelCase							:	str           =  512
  __UpperCAmelCase							:	Any           =  """cuda""" if torch.cuda.is_available() else """cpu"""
  if checkpoint_path.endswith("""safetensors"""		):
    from safetensors import safe_open

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

  # Convert the VAE model.
  __UpperCAmelCase							:	Optional[int]           =  create_vae_diffusers_config(__lowerCamelCase  ,		image_size=__lowerCamelCase		)
  __UpperCAmelCase							:	Union[str, Any]           =  custom_convert_ldm_vae_checkpoint(__lowerCamelCase  ,		__lowerCamelCase		)

  __UpperCAmelCase							:	Optional[int]           =  AutoencoderKL(**__lowerCamelCase		)
  vae.load_state_dict(__lowerCamelCase		)
  vae.save_pretrained(__lowerCamelCase		)


if __name__ == "__main__":
       a		:       List[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.")

       a		:       Optional[int]			     = parser.parse_args()

       vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)


