

import argparse

import torch

from transformers import (
    SpeechTaConfig,
    SpeechTaFeatureExtractor,
    SpeechTaForSpeechToSpeech,
    SpeechTaForSpeechToText,
    SpeechTaForTextToSpeech,
    SpeechTaProcessor,
    SpeechTaTokenizer,
    logging,
)
from transformers.tokenization_utils import AddedToken


logging.set_verbosity_info()
A_ :				List[str]						 =    logging.get_logger('transformers.models.speecht5')

A_ :				List[str]						 =    {
    'speech_encoder_prenet.layer_norm': 'speecht5.encoder.prenet.feature_projection.layer_norm',
    'speech_encoder_prenet.post_extract_proj': 'speecht5.encoder.prenet.feature_projection.projection',
    'speech_encoder_prenet.pos_conv.0': 'speecht5.encoder.prenet.pos_conv_embed.conv',
    'speech_encoder_prenet.mask_emb': 'speecht5.encoder.prenet.masked_spec_embed',
}
A_ :				int						 =    {
    'text_encoder_prenet.encoder_prenet.0': 'speecht5.encoder.prenet.embed_tokens',
    'text_encoder_prenet.encoder_prenet.1.alpha': 'speecht5.encoder.prenet.encode_positions.alpha',
}
A_ :				str						 =    {
    'speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0': 'speecht5.decoder.prenet.layers.0',
    'speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0': 'speecht5.decoder.prenet.layers.1',
    'speech_decoder_prenet.decoder_prenet.0.1': 'speecht5.decoder.prenet.final_layer',
    'speech_decoder_prenet.decoder_prenet.1.alpha': 'speecht5.decoder.prenet.encode_positions.alpha',
    'speech_decoder_prenet.spkembs_layer.0': 'speecht5.decoder.prenet.speaker_embeds_layer',
}
A_ :				Any						 =    {
    'speech_decoder_postnet.feat_out': 'speech_decoder_postnet.feat_out',
    'speech_decoder_postnet.prob_out': 'speech_decoder_postnet.prob_out',
    'speech_decoder_postnet.postnet.postnet.0.0': 'speech_decoder_postnet.layers.0.conv',
    'speech_decoder_postnet.postnet.postnet.0.1': 'speech_decoder_postnet.layers.0.batch_norm',
    'speech_decoder_postnet.postnet.postnet.1.0': 'speech_decoder_postnet.layers.1.conv',
    'speech_decoder_postnet.postnet.postnet.1.1': 'speech_decoder_postnet.layers.1.batch_norm',
    'speech_decoder_postnet.postnet.postnet.2.0': 'speech_decoder_postnet.layers.2.conv',
    'speech_decoder_postnet.postnet.postnet.2.1': 'speech_decoder_postnet.layers.2.batch_norm',
    'speech_decoder_postnet.postnet.postnet.3.0': 'speech_decoder_postnet.layers.3.conv',
    'speech_decoder_postnet.postnet.postnet.3.1': 'speech_decoder_postnet.layers.3.batch_norm',
    'speech_decoder_postnet.postnet.postnet.4.0': 'speech_decoder_postnet.layers.4.conv',
    'speech_decoder_postnet.postnet.postnet.4.1': 'speech_decoder_postnet.layers.4.batch_norm',
}
A_ :				Any						 =    {
    'text_decoder_prenet.embed_tokens': 'speecht5.decoder.prenet.embed_tokens',
}
A_ :				int						 =    {
    'text_decoder_postnet.output_projection': 'text_decoder_postnet.lm_head',
}
A_ :				Any						 =    {
    'encoder.layers.*.self_attn.k_proj': 'speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj',
    'encoder.layers.*.self_attn.v_proj': 'speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj',
    'encoder.layers.*.self_attn.q_proj': 'speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj',
    'encoder.layers.*.self_attn.out_proj': 'speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj',
    'encoder.layers.*.self_attn_layer_norm': 'speecht5.encoder.wrapped_encoder.layers.*.layer_norm',
    'encoder.layers.*.fc1': 'speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense',
    'encoder.layers.*.fc2': 'speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense',
    'encoder.layers.*.final_layer_norm': 'speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm',
    'encoder.layer_norm': 'speecht5.encoder.wrapped_encoder.layer_norm',
    'encoder.pos_emb.pe_k': 'speecht5.encoder.wrapped_encoder.embed_positions.pe_k',
}
A_ :				Optional[Any]						 =    {
    'decoder.layers.*.self_attn.k_proj': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj',
    'decoder.layers.*.self_attn.v_proj': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj',
    'decoder.layers.*.self_attn.q_proj': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj',
    'decoder.layers.*.self_attn.out_proj': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj',
    'decoder.layers.*.self_attn_layer_norm': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm',
    'decoder.layers.*.encoder_attn.k_proj': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj',
    'decoder.layers.*.encoder_attn.v_proj': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj',
    'decoder.layers.*.encoder_attn.q_proj': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj',
    'decoder.layers.*.encoder_attn.out_proj': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj',
    'decoder.layers.*.encoder_attn_layer_norm': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm',
    'decoder.layers.*.fc1': 'speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense',
    'decoder.layers.*.fc2': 'speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense',
    'decoder.layers.*.final_layer_norm': 'speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm',
}
A_ :				str						 =    {
    **MAPPING_SPEECH_ENCODER_PRENET,
    **MAPPING_ENCODER,
    **MAPPING_DECODER,
    **MAPPING_TEXT_DECODER_PRENET,
    **MAPPING_TEXT_DECODER_POSTNET,
}
A_ :				str						 =    {
    **MAPPING_TEXT_ENCODER_PRENET,
    **MAPPING_ENCODER,
    **MAPPING_DECODER,
    **MAPPING_SPEECH_DECODER_PRENET,
    **MAPPING_SPEECH_DECODER_POSTNET,
}
A_ :				Union[str, Any]						 =    {
    **MAPPING_SPEECH_ENCODER_PRENET,
    **MAPPING_ENCODER,
    **MAPPING_DECODER,
    **MAPPING_SPEECH_DECODER_PRENET,
    **MAPPING_SPEECH_DECODER_POSTNET,
}
A_ :				int						 =    []
A_ :				Optional[Any]						 =    [
    'encoder.version',
    'encoder.layers.*.norm_k.weight',
    'encoder.layers.*.norm_k.bias',
    'decoder.version',
    'decoder.layers.*.norm_k.weight',
    'decoder.layers.*.norm_k.bias',
    'decoder.pos_emb.pe_k',
    'speech_encoder_prenet.embed_positions._float_tensor',
    'text_decoder_prenet.embed_positions._float_tensor',
]
A_ :				Optional[Any]						 =    IGNORE_KEYS + [
    'encoder.proj',
    'text_encoder_prenet.*',
    'speech_decoder_prenet.*',
    'speech_decoder_postnet.*',
]
A_ :				Union[str, Any]						 =    IGNORE_KEYS + [
    'encoder.proj',
    'speech_encoder_prenet.*',
    'text_decoder_prenet.*',
    'text_decoder_postnet.*',
]
A_ :				Optional[int]						 =    IGNORE_KEYS + [
    'encoder.proj',
    'text_encoder_prenet.*',
    'text_decoder_prenet.*',
    'text_decoder_postnet.*',
]

def 		UpperCamelCase      (lowercase_:				List[str]					,   lowercase_:				str					,   lowercase_:				str					,   lowercase_:				Union[str, Any]					,   lowercase_:				Optional[int]      )  ->   int:
	for attribute in key.split("""."""      ):
		A__							:					Dict       =	getattr(lowercase_					,   lowercase_      )

	if weight_type is not None:
		A__							:					Tuple       =	getattr(lowercase_					,   lowercase_      ).shape
	else:
		A__							:					int       =	hf_pointer.shape

	if hf_shape != value.shape:
		raise ValueError(
		    f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"""
		    f""" {value.shape} for {full_name}"""      )

	if weight_type == "weight":
		A__							:					Any       =	value
	elif weight_type == "weight_g":
		A__							:					Union[str, Any]       =	value
	elif weight_type == "weight_v":
		A__							:					Optional[Any]       =	value
	elif weight_type == "bias":
		A__							:					str       =	value
	elif weight_type == "running_mean":
		A__							:					List[Any]       =	value
	elif weight_type == "running_var":
		A__							:					str       =	value
	elif weight_type == "num_batches_tracked":
		A__							:					List[Any]       =	value
	else:
		A__							:					Optional[Any]       =	value

	logger.info(f"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}."""      )

def 		UpperCamelCase      (lowercase_:				Optional[Any]					,   lowercase_:				Optional[int]      )  ->   str:
	for key in ignore_keys:
		if key.endswith(""".*"""      ):
			if name.startswith(key[:-1]      ):
				return True
		elif ".*." in key:
			A__     ,     A__							:					List[Any]       =	key.split(""".*."""      )
			if prefix in name and suffix in name:
				return True
		elif key in name:
			return True
	return False

def 		UpperCamelCase      (lowercase_:				Dict					,   lowercase_:				List[str]					,   lowercase_:				Optional[Any]      )  ->   Optional[int]:
	A__							:					Any       =	[]

	if task == "s2t":
		A__							:					Any       =	hf_model.speechta.encoder.prenet.feature_encoder
		A__							:					Optional[Any]       =	MAPPING_S2T
		A__							:					List[Any]       =	IGNORE_KEYS_S2T
	elif task == "t2s":
		A__							:					Any       =	None
		A__							:					Optional[int]       =	MAPPING_T2S
		A__							:					Optional[int]       =	IGNORE_KEYS_T2S
	elif task == "s2s":
		A__							:					Tuple       =	hf_model.speechta.encoder.prenet.feature_encoder
		A__							:					List[str]       =	MAPPING_S2S
		A__							:					Dict       =	IGNORE_KEYS_S2S
	else:
		raise ValueError(f"""Unsupported task: {task}"""      )

	for name, value in fairseq_dict.items():
		if should_ignore(lowercase_					,   lowercase_      ):
			logger.info(f"""{name} was ignored"""      )
			continue

		A__							:					Optional[Any]       =	False
		if "conv_layers" in name:
			load_conv_layer(
			    lowercase_					,   lowercase_					,   lowercase_					,   lowercase_					,   hf_model.config.feat_extract_norm == """group"""					,   )
			A__							:					Any       =	True
		else:
			for key, mapped_key in MAPPING.items():
				# mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key

				if "*" in key:
					A__     ,     A__							:					Tuple       =	key.split(""".*."""      )
					if prefix in name and suffix in name:
						A__							:					Optional[Any]       =	suffix

                # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
				if key in name:
					A__							:					Dict       =	True
					if "*" in mapped_key:
						A__							:					int       =	name.split(lowercase_      )[0].split("""."""      )[-2]
						A__							:					List[str]       =	mapped_key.replace("""*"""					,   lowercase_      )
					if "weight_g" in name:
						A__							:					Optional[Any]       =	"""weight_g"""
					elif "weight_v" in name:
						A__							:					List[Any]       =	"""weight_v"""
					elif "bias" in name:
						A__							:					int       =	"""bias"""
					elif "weight" in name:
						A__							:					Any       =	"""weight"""
					elif "running_mean" in name:
						A__							:					Optional[Any]       =	"""running_mean"""
					elif "running_var" in name:
						A__							:					Tuple       =	"""running_var"""
					elif "num_batches_tracked" in name:
						A__							:					Dict       =	"""num_batches_tracked"""
					else:
						A__							:					Union[str, Any]       =	None
					set_recursively(lowercase_					,   lowercase_					,   lowercase_					,   lowercase_					,   lowercase_      )
				continue
		if not is_used:
			unused_weights.append(lowercase_      )

	logger.warning(f"""Unused weights: {unused_weights}"""      )

def 		UpperCamelCase      (lowercase_:				Union[str, Any]					,   lowercase_:				Any					,   lowercase_:				Optional[Any]					,   lowercase_:				str					,   lowercase_:				Any      )  ->   List[str]:
	A__							:					int       =	full_name.split("""conv_layers."""      )[-1]
	A__							:					Optional[int]       =	name.split("""."""      )
	A__							:					Any       =	int(items[0]      )
	A__							:					Dict       =	int(items[1]      )

	if type_id == 0:
		if "bias" in name:
			if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
				raise ValueError(
				    f"""{full_name} has size {value.shape}, but"""
				    f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."""      )
			A__							:					Optional[int]       =	value
			logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}."""      )
		elif "weight" in name:
			if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
				raise ValueError(
				    f"""{full_name} has size {value.shape}, but"""
				    f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."""      )
			A__							:					List[str]       =	value
			logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}."""      )
	elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
		if "bias" in name:
			if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
				raise ValueError(
				    f"""{full_name} has size {value.shape}, but"""
				    f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found."""      )
			A__							:					int       =	value
			logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""      )
		elif "weight" in name:
			if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
				raise ValueError(
				    f"""{full_name} has size {value.shape}, but"""
				    f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found."""      )
			A__							:					str       =	value
			logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""      )
	else:
		unused_weights.append(lowercase_      )

@torch.no_grad()
def 		UpperCamelCase      (lowercase_:				Union[str, Any]					,   lowercase_:				int					,   lowercase_:				str					,   lowercase_:				List[Any]=None					,   lowercase_:				Tuple=None					,   lowercase_:				Dict=None					,   )  ->   Union[str, Any]:
	if config_path is not None:
		A__							:					Tuple       =	SpeechTaConfig.from_pretrained(lowercase_      )
	else:
		A__							:					Tuple       =	SpeechTaConfig()

	if task == "s2t":
		A__							:					Optional[int]       =	config.max_text_positions
		A__							:					Any       =	SpeechTaForSpeechToText(lowercase_      )
	elif task == "t2s":
		A__							:					List[Any]       =	1876
		A__							:					str       =	600
		A__							:					List[Any]       =	config.max_speech_positions
		A__							:					Tuple       =	SpeechTaForTextToSpeech(lowercase_      )
	elif task == "s2s":
		A__							:					Dict       =	1876
		A__							:					int       =	config.max_speech_positions
		A__							:					Any       =	SpeechTaForSpeechToSpeech(lowercase_      )
	else:
		raise ValueError(f"""Unknown task name: {task}"""      )

	if vocab_path:
		A__							:					Any       =	SpeechTaTokenizer(lowercase_					,   model_max_length=config.max_text_positions      )

		# Mask token behaves like a normal word, i.e. include the space before it
		A__							:					Optional[Any]       =	AddedToken("""<mask>"""					,   lstrip=lowercase_					,   rstrip=lowercase_      )
		A__							:					List[Any]       =	mask_token
		tokenizer.add_special_tokens({"""mask_token""": mask_token}      )
		tokenizer.add_tokens(["""<ctc_blank>"""]      )

	A__							:					Dict       =	SpeechTaFeatureExtractor()
	A__							:					List[Any]       =	SpeechTaProcessor(tokenizer=lowercase_					,   feature_extractor=lowercase_      )
	processor.save_pretrained(lowercase_      )

	A__							:					List[Any]       =	torch.load(lowercase_      )
	recursively_load_weights(fairseq_checkpoint["""model"""]					,   lowercase_					,   lowercase_      )

	model.save_pretrained(lowercase_      )

	if repo_id:
		print("""Pushing to the hub..."""      )
		processor.push_to_hub(lowercase_      )
		model.push_to_hub(lowercase_      )


if __name__ == "__main__":
	A_ :				Union[str, Any]						 =    argparse.ArgumentParser()
	parser.add_argument(
	    '--task',
	    default='s2t',
	    type=str,
	    help='Type of the SpeechT5 model you\'d like to convert. Should be one of \'s2t\', \'t2s\', \'s2s\'.',
	)
	parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to fairseq checkpoint')
	parser.add_argument('--vocab_path', default=None, type=str, help='Path to SentencePiece model')
	parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
	parser.add_argument(
	    '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.'
	)
	parser.add_argument(
	    '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.'
	)

	A_ :				List[str]						 =    parser.parse_args()
	convert_speechta_checkpoint(
	    args.task,
	    args.checkpoint_path,
	    args.pytorch_dump_folder_path,
	    args.config_path,
	    args.vocab_path,
	    args.push_to_hub,
	)






import argparse
import hashlib
import os
import urllib
import warnings

import torch
from torch import nn
from tqdm import tqdm

from transformers import WhisperConfig, WhisperForConditionalGeneration


A_ :				Dict						 =    {
    'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt',
    'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt',
    'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt',
    'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt',
    'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt',
    'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt',
    'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt',
    'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt',
    'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt',
    'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt',
}

def 		UpperCamelCase      (lowercase_:				Optional[Any]      )  ->   Optional[int]:
	A__							:					List[Any]       =	["""layers""", """blocks"""]
	for k in ignore_keys:
		state_dict.pop(lowercase_					,   lowercase_      )


A_ :				Any						 =    {
    'blocks': 'layers',
    'mlp.0': 'fc1',
    'mlp.2': 'fc2',
    'mlp_ln': 'final_layer_norm',
    '.attn.query': '.self_attn.q_proj',
    '.attn.key': '.self_attn.k_proj',
    '.attn.value': '.self_attn.v_proj',
    '.attn_ln': '.self_attn_layer_norm',
    '.attn.out': '.self_attn.out_proj',
    '.cross_attn.query': '.encoder_attn.q_proj',
    '.cross_attn.key': '.encoder_attn.k_proj',
    '.cross_attn.value': '.encoder_attn.v_proj',
    '.cross_attn_ln': '.encoder_attn_layer_norm',
    '.cross_attn.out': '.encoder_attn.out_proj',
    'decoder.ln.': 'decoder.layer_norm.',
    'encoder.ln.': 'encoder.layer_norm.',
    'token_embedding': 'embed_tokens',
    'encoder.positional_embedding': 'encoder.embed_positions.weight',
    'decoder.positional_embedding': 'decoder.embed_positions.weight',
    'ln_post': 'layer_norm',
}

def 		UpperCamelCase      (lowercase_:				str      )  ->   Any:
	A__							:					Dict       =	list(s_dict.keys()      )
	for key in keys:
		A__							:					List[str]       =	key
		for k, v in WHISPER_MAPPING.items():
			if k in key:
				A__							:					List[Any]       =	new_key.replace(lowercase_					,   lowercase_      )

		print(f"""{key} -> {new_key}"""      )

		A__							:					Tuple       =	s_dict.pop(lowercase_      )
	return s_dict

def 		UpperCamelCase      (lowercase_:				Tuple      )  ->   Optional[int]:
	A__     ,     A__							:					Any       =	emb.weight.shape
	A__							:					str       =	nn.Linear(lowercase_					,   lowercase_					,   bias=lowercase_      )
	A__							:					Union[str, Any]       =	emb.weight.data
	return lin_layer

def 		UpperCamelCase      (lowercase_:				str					,   lowercase_:				str      )  ->   bytes:
	os.makedirs(lowercase_					,   exist_ok=lowercase_      )
	A__							:					Tuple       =	os.path.basename(lowercase_      )

	A__							:					int       =	url.split("""/"""      )[-2]
	A__							:					Dict       =	os.path.join(lowercase_					,   lowercase_      )

	if os.path.exists(lowercase_      ) and not os.path.isfile(lowercase_      ):
		raise RuntimeError(f"""{download_target} exists and is not a regular file"""      )

	if os.path.isfile(lowercase_      ):
		A__							:					Optional[Any]       =	open(lowercase_					,   """rb"""      ).read()
		if hashlib.shaaaa(lowercase_      ).hexdigest() == expected_shaaaa:
			return model_bytes
		else:
			warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file"""      )

	with urllib.request.urlopen(lowercase_      ) as source, open(lowercase_					,   """wb"""      ) as output:
		with tqdm(
		    total=int(source.info().get("""Content-Length"""      )      )					,   ncols=80					,   unit="""iB"""					,   unit_scale=lowercase_					,   unit_divisor=1024      ) as loop:
			while True:
				A__							:					Any       =	source.read(8192      )
				if not buffer:
					break

				output.write(lowercase_      )
				loop.update(len(lowercase_      )      )

	A__							:					Dict       =	open(lowercase_					,   """rb"""      ).read()
	if hashlib.shaaaa(lowercase_      ).hexdigest() != expected_shaaaa:
		raise RuntimeError(
		    """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model."""      )

	return model_bytes

def 		UpperCamelCase      (lowercase_:				List[Any]					,   lowercase_:				Tuple      )  ->   Optional[Any]:
	if ".pt" not in checkpoint_path:
		A__							:					Tuple       =	_download(_MODELS[checkpoint_path]      )
	else:
		A__							:					Optional[int]       =	torch.load(lowercase_					,   map_location="""cpu"""      )
	A__							:					str       =	original_checkpoint["""dims"""]
	A__							:					List[Any]       =	original_checkpoint["""model_state_dict"""]
	A__							:					Optional[Any]       =	state_dict["""decoder.token_embedding.weight"""]
	remove_ignore_keys_(lowercase_      )
	rename_keys(lowercase_      )
	A__							:					List[str]       =	True
	A__							:					Optional[Any]       =	state_dict["""decoder.layers.0.fc1.weight"""].shape[0]

	A__							:					List[Any]       =	WhisperConfig(
	    vocab_size=dimensions["""n_vocab"""]					,   encoder_ffn_dim=lowercase_					,   decoder_ffn_dim=lowercase_					,   num_mel_bins=dimensions["""n_mels"""]					,   d_model=dimensions["""n_audio_state"""]					,   max_target_positions=dimensions["""n_text_ctx"""]					,   encoder_layers=dimensions["""n_audio_layer"""]					,   encoder_attention_heads=dimensions["""n_audio_head"""]					,   decoder_layers=dimensions["""n_text_layer"""]					,   decoder_attention_heads=dimensions["""n_text_state"""]					,   max_source_positions=dimensions["""n_audio_ctx"""]					,   )

	A__							:					Optional[Any]       =	WhisperForConditionalGeneration(lowercase_      )
	A__     ,     A__							:					List[Any]       =	model.model.load_state_dict(lowercase_					,   strict=lowercase_      )
	if len(lowercase_      ) > 0 and not set(lowercase_      ) <= {
	    "encoder.embed_positions.weights",
	    "decoder.embed_positions.weights",
	}:
		raise ValueError(
		    """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights`  are allowed to be missing,"""
		    f""" but all the following weights are missing {missing}"""      )

	if tie_embeds:
		A__							:					Any       =	make_linear_from_emb(model.model.decoder.embed_tokens      )
	else:
		A__							:					str       =	proj_out_weights

	model.save_pretrained(lowercase_      )


if __name__ == "__main__":
	A_ :				Any						 =    argparse.ArgumentParser()
	# # Required parameters
	parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints')
	parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
	A_ :				Tuple						 =    parser.parse_args()

	convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)



