





"""simple docstring"""





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


_UpperCamelCase							=      {
    '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 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							__lowerCamelCase      :      Any         =['''layers''', '''blocks''']
							for k in ignore_keys:
														state_dict.pop(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )


_UpperCamelCase							=      {
    '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 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Union[str, Any]   ):


							'''simple docstring'''







							__lowerCamelCase      :      List[str]         =list(s_dict.keys()   )
							for key in keys:
														__lowerCamelCase      :      Optional[Any]         =key
														for k, v in WHISPER_MAPPING.items():
																					if k in key:
																												__lowerCamelCase      :      Dict         =new_key.replace(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )

														print(F'{key} -> {new_key}'   )

														__lowerCamelCase      :      Optional[Any]         =s_dict.pop(SCREAMING_SNAKE_CASE   )
							return s_dict



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Optional[Any]   ):


							'''simple docstring'''







							__lowerCamelCase      :      Union[str, Any]         =emb.weight.shape
							__lowerCamelCase      :      Tuple         =nn.Linear(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE    ,						bias=SCREAMING_SNAKE_CASE   )
							__lowerCamelCase      :      Union[str, Any]         =emb.weight.data
							return lin_layer



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							str    ,						SCREAMING_SNAKE_CASE       :							str   ):


							'''simple docstring'''







							os.makedirs(SCREAMING_SNAKE_CASE    ,						exist_ok=SCREAMING_SNAKE_CASE   )
							__lowerCamelCase      :      Tuple         =os.path.basename(SCREAMING_SNAKE_CASE   )

							__lowerCamelCase      :      Dict         =url.split('''/'''   )[-2]
							__lowerCamelCase      :      List[Any]         =os.path.join(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )

							if os.path.exists(SCREAMING_SNAKE_CASE   ) and not os.path.isfile(SCREAMING_SNAKE_CASE   ):
														raise RuntimeError(F'{download_target} exists and is not a regular file'   )

							if os.path.isfile(SCREAMING_SNAKE_CASE   ):
														__lowerCamelCase      :      int         =open(SCREAMING_SNAKE_CASE    ,						'''rb'''   ).read()
														if hashlib.shaaaa(SCREAMING_SNAKE_CASE   ).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(SCREAMING_SNAKE_CASE   ) as source, open(SCREAMING_SNAKE_CASE    ,						'''wb'''   ) as output:
														with tqdm(
														    total=int(source.info().get('''Content-Length'''   )   )    ,						ncols=80    ,						unit='''iB'''    ,						unit_scale=SCREAMING_SNAKE_CASE    ,						unit_divisor=1024   ) as loop:
																					while True:
																												__lowerCamelCase      :      List[str]         =source.read(8192   )
																												if not buffer:
																																			break

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

							__lowerCamelCase      :      Optional[int]         =open(SCREAMING_SNAKE_CASE    ,						'''rb'''   ).read()
							if hashlib.shaaaa(SCREAMING_SNAKE_CASE   ).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 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Union[str, Any]    ,						SCREAMING_SNAKE_CASE       :							Union[str, Any]   ):


							'''simple docstring'''







							if ".pt" not in checkpoint_path:
														__lowerCamelCase      :      str         =_download(_MODELS[checkpoint_path]   )
							else:
														__lowerCamelCase      :      List[str]         =torch.load(SCREAMING_SNAKE_CASE    ,						map_location='''cpu'''   )
							__lowerCamelCase      :      List[str]         =original_checkpoint['''dims''']
							__lowerCamelCase      :      Dict         =original_checkpoint['''model_state_dict''']
							__lowerCamelCase      :      Tuple         =state_dict['''decoder.token_embedding.weight''']
							remove_ignore_keys_(SCREAMING_SNAKE_CASE   )
							rename_keys(SCREAMING_SNAKE_CASE   )
							__lowerCamelCase      :      List[str]         =True
							__lowerCamelCase      :      Tuple         =state_dict['''decoder.layers.0.fc1.weight'''].shape[0]

							__lowerCamelCase      :      List[str]         =WhisperConfig(
							    vocab_size=dimensions['''n_vocab''']    ,						encoder_ffn_dim=SCREAMING_SNAKE_CASE    ,						decoder_ffn_dim=SCREAMING_SNAKE_CASE    ,						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''']    ,						)

							__lowerCamelCase      :      Union[str, Any]         =WhisperForConditionalGeneration(SCREAMING_SNAKE_CASE   )
							__lowerCamelCase      :      Any         =model.model.load_state_dict(SCREAMING_SNAKE_CASE    ,						strict=SCREAMING_SNAKE_CASE   )
							if len(SCREAMING_SNAKE_CASE   ) > 0 and not set(SCREAMING_SNAKE_CASE   ) <= {
							    "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:
														__lowerCamelCase      :      Union[str, Any]         =make_linear_from_emb(model.model.decoder.embed_tokens   )
							else:
														__lowerCamelCase      :      int         =proj_out_weights

							model.save_pretrained(SCREAMING_SNAKE_CASE   )


if __name__ == "__main__":
							_UpperCamelCase							=      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.')
							_UpperCamelCase							=      parser.parse_args()

							convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)











"""simple docstring"""





from typing import Any
class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""




				def __init__(     self  :Tuple						,    __lowercase  :Any			):
											__lowerCamelCase      :      str         =data
											__lowerCamelCase      :      Any         =None




				def __repr__(     self  :Optional[Any]			):
											return f'Node({self.data})'

class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""




				def __init__(     self  :Optional[int]			):
											__lowerCamelCase      :      Union[str, Any]         =None




				def __iter__(     self  :Optional[int]			):
											__lowerCamelCase      :      Optional[Any]         =self.head
											while node:
																		yield node.data
																		__lowerCamelCase      :      str         =node.next




				def __len__(     self  :Any			):
											return sum(1 for _ in self			)




				def __repr__(     self  :Any			):
											return "->".join([str(__lowercase			) for item in self]			)




				def __getitem__(     self  :Dict						,    __lowercase  :int			):
											if not 0 <= index < len(self			):
																		raise ValueError('''list index out of range.'''			)
											for i, node in enumerate(self			):
																		if i == index:
																									return node
											return None




				def __setitem__(     self  :Dict						,    __lowercase  :int						,    __lowercase  :Any			):
											if not 0 <= index < len(self			):
																		raise ValueError('''list index out of range.'''			)
											__lowerCamelCase      :      Optional[Any]         =self.head
											for _ in range(__lowercase			):
																		__lowerCamelCase      :      List[str]         =current.next
											__lowerCamelCase      :      Optional[int]         =data




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :Any			):
											self.insert_nth(len(self			)						,    __lowercase			)




				def 					__lowercase  (     self  :int						,    __lowercase  :Any			):
											self.insert_nth(0						,    __lowercase			)




				def 					__lowercase  (     self  :Dict						,    __lowercase  :int						,    __lowercase  :Any			):
											if not 0 <= index <= len(self			):
																		raise IndexError('''list index out of range'''			)
											__lowerCamelCase      :      List[Any]         =Node(__lowercase			)
											if self.head is None:
																		__lowerCamelCase      :      List[Any]         =new_node
											elif index == 0:
																		__lowerCamelCase      :      Optional[Any]         =self.head  # link new_node to head
																		__lowerCamelCase      :      Optional[Any]         =new_node
											else:
																		__lowerCamelCase      :      str         =self.head
																		for _ in range(index - 1			):
																									__lowerCamelCase      :      Any         =temp.next
																		__lowerCamelCase      :      List[Any]         =temp.next
																		__lowerCamelCase      :      List[Any]         =new_node




				def 					__lowercase  (     self  :Tuple			):  # print every node data
											print(self			)




				def 					__lowercase  (     self  :List[str]			):
											return self.delete_nth(0			)




				def 					__lowercase  (     self  :Any			):  # delete from tail
											return self.delete_nth(len(self			) - 1			)




				def 					__lowercase  (     self  :Dict						,    __lowercase  :int = 0			):
											if not 0 <= index <= len(self			) - 1:  # test if index is valid
																		raise IndexError('''List index out of range.'''			)
											__lowerCamelCase      :      List[Any]         =self.head  # default first node
											if index == 0:
																		__lowerCamelCase      :      int         =self.head.next
											else:
																		__lowerCamelCase      :      int         =self.head
																		for _ in range(index - 1			):
																									__lowerCamelCase      :      str         =temp.next
																		__lowerCamelCase      :      int         =temp.next
																		__lowerCamelCase      :      Optional[Any]         =temp.next.next
											return delete_node.data




				def 					__lowercase  (     self  :Any			):
											return self.head is None




				def 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      Any         =None
											__lowerCamelCase      :      Optional[int]         =self.head

											while current:
																		# Store the current node's next node.
																		__lowerCamelCase      :      Any         =current.next
																		# Make the current node's next point backwards
																		__lowerCamelCase      :      Optional[Any]         =prev
																		# Make the previous node be the current node
																		__lowerCamelCase      :      List[str]         =current
																		# Make the current node the next node (to progress iteration)
																		__lowerCamelCase      :      Tuple         =next_node
											# Return prev in order to put the head at the end
											__lowerCamelCase      :      List[str]         =prev



def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							__lowerCamelCase      :      Tuple         =LinkedList()
							assert linked_list.is_empty() is True
							assert str(SCREAMING_SNAKE_CASE   ) == ""

							try:
														linked_list.delete_head()
														raise AssertionError  # This should not happen.
							except IndexError:
														assert True  # This should happen.

							try:
														linked_list.delete_tail()
														raise AssertionError  # This should not happen.
							except IndexError:
														assert True  # This should happen.

							for i in range(10   ):
														assert len(SCREAMING_SNAKE_CASE   ) == i
														linked_list.insert_nth(SCREAMING_SNAKE_CASE    ,						i + 1   )
							assert str(SCREAMING_SNAKE_CASE   ) == "->".join(str(SCREAMING_SNAKE_CASE   ) for i in range(1    ,						11   )   )

							linked_list.insert_head(0   )
							linked_list.insert_tail(11   )
							assert str(SCREAMING_SNAKE_CASE   ) == "->".join(str(SCREAMING_SNAKE_CASE   ) for i in range(0    ,						12   )   )

							assert linked_list.delete_head() == 0
							assert linked_list.delete_nth(9   ) == 10
							assert linked_list.delete_tail() == 11
							assert len(SCREAMING_SNAKE_CASE   ) == 9
							assert str(SCREAMING_SNAKE_CASE   ) == "->".join(str(SCREAMING_SNAKE_CASE   ) for i in range(1    ,						10   )   )

							assert all(linked_list[i] == i + 1 for i in range(0    ,						9   )   ) is True

							for i in range(0    ,						9   ):
														__lowerCamelCase      :      List[Any]         =-i
							assert all(linked_list[i] == -i for i in range(0    ,						9   )   ) is True

							linked_list.reverse()
							assert str(SCREAMING_SNAKE_CASE   ) == "->".join(str(SCREAMING_SNAKE_CASE   ) for i in range(-8    ,						1   )   )



def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							__lowerCamelCase      :      Any         =[
							    -9,
							    100,
							    Node(77345112   ),
							    '''dlrow olleH''',
							    7,
							    5555,
							    0,
							    -192.55_555,
							    '''Hello, world!''',
							    77.9,
							    Node(10   ),
							    None,
							    None,
							    12.20,
							]
							__lowerCamelCase      :      str         =LinkedList()

							for i in test_input:
														linked_list.insert_tail(SCREAMING_SNAKE_CASE   )

							# Check if it's empty or not
							assert linked_list.is_empty() is False
							assert (
							    str(SCREAMING_SNAKE_CASE   ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
							    "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
							)

							# Delete the head
							__lowerCamelCase      :      str         =linked_list.delete_head()
							assert result == -9
							assert (
							    str(SCREAMING_SNAKE_CASE   ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
							    "Hello, world!->77.9->Node(10)->None->None->12.2"
							)

							# Delete the tail
							__lowerCamelCase      :      Union[str, Any]         =linked_list.delete_tail()
							assert result == 12.2
							assert (
							    str(SCREAMING_SNAKE_CASE   ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
							    "Hello, world!->77.9->Node(10)->None->None"
							)

							# Delete a node in specific location in linked list
							__lowerCamelCase      :      Union[str, Any]         =linked_list.delete_nth(10   )
							assert result is None
							assert (
							    str(SCREAMING_SNAKE_CASE   ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
							    "Hello, world!->77.9->Node(10)->None"
							)

							# Add a Node instance to its head
							linked_list.insert_head(Node('''Hello again, world!'''   )   )
							assert (
							    str(SCREAMING_SNAKE_CASE   )
							    == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
							    "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
							)

							# Add None to its tail
							linked_list.insert_tail(SCREAMING_SNAKE_CASE   )
							assert (
							    str(SCREAMING_SNAKE_CASE   )
							    == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
							    "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
							)

							# Reverse the linked list
							linked_list.reverse()
							assert (
							    str(SCREAMING_SNAKE_CASE   )
							    == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
							    "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
							)



def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							from doctest import testmod

							testmod()

							__lowerCamelCase      :      Optional[Any]         =LinkedList()
							linked_list.insert_head(input('''Inserting 1st at head '''   ).strip()   )
							linked_list.insert_head(input('''Inserting 2nd at head '''   ).strip()   )
							print('''\nPrint list:'''   )
							linked_list.print_list()
							linked_list.insert_tail(input('''\nInserting 1st at tail '''   ).strip()   )
							linked_list.insert_tail(input('''Inserting 2nd at tail '''   ).strip()   )
							print('''\nPrint list:'''   )
							linked_list.print_list()
							print('''\nDelete head'''   )
							linked_list.delete_head()
							print('''Delete tail'''   )
							linked_list.delete_tail()
							print('''\nPrint list:'''   )
							linked_list.print_list()
							print('''\nReverse linked list'''   )
							linked_list.reverse()
							print('''\nPrint list:'''   )
							linked_list.print_list()
							print('''\nString representation of linked list:'''   )
							print(SCREAMING_SNAKE_CASE   )
							print('''\nReading/changing Node data using indexing:'''   )
							print(F'Element at Position 1: {linked_list[1]}'   )
							__lowerCamelCase      :      Any         =input('''Enter New Value: '''   ).strip()
							print('''New list:'''   )
							print(SCREAMING_SNAKE_CASE   )
							print(F'length of linked_list is : {len(SCREAMING_SNAKE_CASE   )}'   )


if __name__ == "__main__":
							main()




