



import argparse
import glob
import logging
import os
from argparse import Namespace
from importlib import import_module

import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader, TensorDataset
from utils_ner import TokenClassificationTask


_lowercase     							=						logging.getLogger(__name__)
class 				__A					( A_      ):
			UpperCamelCase					:Optional[int]     =			'''token-classification'''





			def __init__(self							,    __magic_name__				):
						if type(__magic_name__				) == dict:
									lowerCamelCase__ :      Any								=		Namespace(**__magic_name__				)
						lowerCamelCase__ :      str								=		import_module("""tasks"""				)
						try:
									lowerCamelCase__ :      Optional[Any]								=		getattr(__magic_name__							,    hparams.task_type				)
									lowerCamelCase__ :      TokenClassificationTask								=		token_classification_task_clazz()
						except AttributeError:
									raise ValueError(
									    f"Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. "
									    f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}"				)
						lowerCamelCase__ :      Any								=		self.token_classification_task.get_labels(hparams.labels				)
						lowerCamelCase__ :      Tuple								=		CrossEntropyLoss().ignore_index
						super().__init__(__magic_name__							,    len(self.labels				)							,    self.mode				)





			def        _snake_case    (self							,    **__magic_name__				):
						return self.model(**__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      Tuple								=		{"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}
						if self.config.model_type != "distilbert":
									lowerCamelCase__ :      Union[str, Any]								=		(
									    batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None
									)  # XLM and RoBERTa don"t use token_type_ids

						lowerCamelCase__ :      List[str]								=		self(**__magic_name__				)
						lowerCamelCase__ :      Dict								=		outputs[0]
						# tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]}
						return {"loss": loss}





			def        _snake_case    (self				):
						lowerCamelCase__ :      Dict								=		self.hparams
						for mode in ["train", "dev", "test"]:
									lowerCamelCase__ :      List[str]								=		self._feature_file(__magic_name__				)
									if os.path.exists(__magic_name__				) and not args.overwrite_cache:
												logger.info("""Loading features from cached file %s"""							,    __magic_name__				)
												lowerCamelCase__ :      Union[str, Any]								=		torch.load(__magic_name__				)
									else:
												logger.info("""Creating features from dataset file at %s"""							,    args.data_dir				)
												lowerCamelCase__ :      int								=		self.token_classification_task.read_examples_from_file(args.data_dir							,    __magic_name__				)
												lowerCamelCase__ :      Tuple								=		self.token_classification_task.convert_examples_to_features(
												    __magic_name__							,    self.labels							,    args.max_seq_length							,    self.tokenizer							,    cls_token_at_end=bool(self.config.model_type in ["""xlnet"""]				)							,    cls_token=self.tokenizer.cls_token							,    cls_token_segment_id=2 if self.config.model_type in ["""xlnet"""] else 0							,    sep_token=self.tokenizer.sep_token							,    sep_token_extra=__magic_name__							,    pad_on_left=bool(self.config.model_type in ["""xlnet"""]				)							,    pad_token=self.tokenizer.pad_token_id							,    pad_token_segment_id=self.tokenizer.pad_token_type_id							,    pad_token_label_id=self.pad_token_label_id							,    )
												logger.info("""Saving features into cached file %s"""							,    __magic_name__				)
												torch.save(__magic_name__							,    __magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = False				):
						lowerCamelCase__ :      Any								=		self._feature_file(__magic_name__				)
						logger.info("""Loading features from cached file %s"""							,    __magic_name__				)
						lowerCamelCase__ :      Optional[Any]								=		torch.load(__magic_name__				)
						lowerCamelCase__ :      Tuple								=		torch.tensor([f.input_ids for f in features]							,    dtype=torch.long				)
						lowerCamelCase__ :      Optional[Any]								=		torch.tensor([f.attention_mask for f in features]							,    dtype=torch.long				)
						if features[0].token_type_ids is not None:
									lowerCamelCase__ :      str								=		torch.tensor([f.token_type_ids for f in features]							,    dtype=torch.long				)
						else:
									lowerCamelCase__ :      int								=		torch.tensor([0 for f in features]							,    dtype=torch.long				)
									# HACK(we will not use this anymore soon)
						lowerCamelCase__ :      Any								=		torch.tensor([f.label_ids for f in features]							,    dtype=torch.long				)
						return DataLoader(
						    TensorDataset(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__				)							,    batch_size=__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__				):
						"""Compute validation""" ""
						lowerCamelCase__ :      Optional[int]								=		{"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}
						if self.config.model_type != "distilbert":
									lowerCamelCase__ :      Tuple								=		(
									    batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None
									)  # XLM and RoBERTa don"t use token_type_ids
						lowerCamelCase__ :      str								=		self(**__magic_name__				)
						lowerCamelCase__							,lowerCamelCase__ :      List[Any]								=		outputs[:2]
						lowerCamelCase__ :      List[Any]								=		logits.detach().cpu().numpy()
						lowerCamelCase__ :      Dict								=		inputs["""labels"""].detach().cpu().numpy()
						return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}





			def        _snake_case    (self							,    __magic_name__				):
						lowerCamelCase__ :      List[str]								=		torch.stack([x["""val_loss"""] for x in outputs]				).mean()
						lowerCamelCase__ :      Optional[int]								=		np.concatenate([x["""pred"""] for x in outputs]							,    axis=0				)
						lowerCamelCase__ :      List[str]								=		np.argmax(__magic_name__							,    axis=2				)
						lowerCamelCase__ :      Optional[Any]								=		np.concatenate([x["""target"""] for x in outputs]							,    axis=0				)

						lowerCamelCase__ :      Optional[int]								=		dict(enumerate(self.labels				)				)
						lowerCamelCase__ :      List[str]								=		[[] for _ in range(out_label_ids.shape[0]				)]
						lowerCamelCase__ :      Any								=		[[] for _ in range(out_label_ids.shape[0]				)]

						for i in range(out_label_ids.shape[0]				):
									for j in range(out_label_ids.shape[1]				):
												if out_label_ids[i, j] != self.pad_token_label_id:
															out_label_list[i].append(label_map[out_label_ids[i][j]]				)
															preds_list[i].append(label_map[preds[i][j]]				)

						lowerCamelCase__ :      Tuple								=		{
						    """val_loss""": val_loss_mean,
						    """accuracy_score""": accuracy_score(__magic_name__							,    __magic_name__				),
						    """precision""": precision_score(__magic_name__							,    __magic_name__				),
						    """recall""": recall_score(__magic_name__							,    __magic_name__				),
						    """f1""": fa_score(__magic_name__							,    __magic_name__				),
						}

						lowerCamelCase__ :      Dict								=		dict(results.items()				)
						lowerCamelCase__ :      str								=		results
						return ret, preds_list, out_label_list





			def        _snake_case    (self							,    __magic_name__				):
						# when stable
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      str								=		self._eval_end(__magic_name__				)
						lowerCamelCase__ :      Union[str, Any]								=		ret["""log"""]
						return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}





			def        _snake_case    (self							,    __magic_name__				):
						# updating to test_epoch_end instead of deprecated test_end
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Union[str, Any]								=		self._eval_end(__magic_name__				)

						# Converting to the dict required by pl
						# https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\
						# pytorch_lightning/trainer/logging.py#L139
						lowerCamelCase__ :      List[Any]								=		ret["""log"""]
						# `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
						return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}





			@staticmethod
			def        _snake_case    (__magic_name__							,    __magic_name__				):
						# Add NER specific options
						BaseTransformer.add_model_specific_args(__magic_name__							,    __magic_name__				)
						parser.add_argument(
						    """--task_type"""							,    default="""NER"""							,    type=__magic_name__							,    help="""Task type to fine tune in training (e.g. NER, POS, etc)"""				)
						parser.add_argument(
						    """--max_seq_length"""							,    default=128							,    type=__magic_name__							,    help=(
						        """The maximum total input sequence length after tokenization. Sequences longer """
						        """than this will be truncated, sequences shorter will be padded."""
						    )							,    )

						parser.add_argument(
						    """--labels"""							,    default=""""""							,    type=__magic_name__							,    help="""Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""							,    )
						parser.add_argument(
						    """--gpus"""							,    default=0							,    type=__magic_name__							,    help="""The number of GPUs allocated for this, it is by default 0 meaning none"""							,    )

						parser.add_argument(
						    """--overwrite_cache"""							,    action="""store_true"""							,    help="""Overwrite the cached training and evaluation sets"""				)

						return parser


if __name__ == "__main__":
				_lowercase     							=						argparse.ArgumentParser()
				add_generic_args(parser, os.getcwd())
				_lowercase     							=						NERTransformer.add_model_specific_args(parser, os.getcwd())
				_lowercase     							=						parser.parse_args()
				_lowercase     							=						NERTransformer(args)
				_lowercase     							=						generic_train(model, args)

				if args.do_predict:
								# See https://github.com/huggingface/transformers/issues/3159
								# pl use this default format to create a checkpoint:
								# https://github.com/PyTorchLightning/pytorch-lightning/blob/master\
								# /pytorch_lightning/callbacks/model_checkpoint.py#L322
								_lowercase     							=						sorted(glob.glob(os.path.join(args.output_dir, '''checkpoint-epoch=*.ckpt'''), recursive=True))
								_lowercase     							=						model.load_from_checkpoint(checkpoints[-1])
								trainer.test(model)








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


_lowercase     							=						{
    '''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      _A				(UpperCamelCase		:      Any )  ->List[str]:



			'''simple docstring'''







			lowerCamelCase__ :      List[str]								=		["""layers""", """blocks"""]
			for k in ignore_keys:
						state_dict.pop(UpperCamelCase      ,			UpperCamelCase )


_lowercase     							=						{
    '''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      _A				(UpperCamelCase		:      Union[str, Any] )  ->Optional[Any]:



			'''simple docstring'''







			lowerCamelCase__ :      Union[str, Any]								=		list(s_dict.keys() )
			for key in keys:
						lowerCamelCase__ :      Dict								=		key
						for k, v in WHISPER_MAPPING.items():
									if k in key:
												lowerCamelCase__ :      Tuple								=		new_key.replace(UpperCamelCase      ,			UpperCamelCase )

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

						lowerCamelCase__ :      int								=		s_dict.pop(UpperCamelCase )
			return s_dict






def      _A				(UpperCamelCase		:      List[Any] )  ->Optional[Any]:



			'''simple docstring'''







			lowerCamelCase__							,lowerCamelCase__ :      int								=		emb.weight.shape
			lowerCamelCase__ :      Optional[int]								=		nn.Linear(UpperCamelCase      ,			UpperCamelCase      ,			bias=UpperCamelCase )
			lowerCamelCase__ :      List[str]								=		emb.weight.data
			return lin_layer






def      _A				(UpperCamelCase		:      str      ,			UpperCamelCase		:      str )  ->bytes:



			'''simple docstring'''







			os.makedirs(UpperCamelCase      ,			exist_ok=UpperCamelCase )
			lowerCamelCase__ :      Any								=		os.path.basename(UpperCamelCase )

			lowerCamelCase__ :      int								=		url.split("""/""" )[-2]
			lowerCamelCase__ :      Optional[int]								=		os.path.join(UpperCamelCase      ,			UpperCamelCase )

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

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

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

			lowerCamelCase__ :      Any								=		open(UpperCamelCase      ,			"""rb""" ).read()
			if hashlib.shaaaa(UpperCamelCase ).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      _A				(UpperCamelCase		:      Dict      ,			UpperCamelCase		:      Any )  ->Optional[Any]:



			'''simple docstring'''







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

			lowerCamelCase__ :      List[str]								=		WhisperConfig(
			    vocab_size=dimensions["""n_vocab"""]      ,			encoder_ffn_dim=UpperCamelCase      ,			decoder_ffn_dim=UpperCamelCase      ,			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__ :      List[str]								=		WhisperForConditionalGeneration(UpperCamelCase )
			lowerCamelCase__							,lowerCamelCase__ :      str								=		model.model.load_state_dict(UpperCamelCase      ,			strict=UpperCamelCase )
			if len(UpperCamelCase ) > 0 and not set(UpperCamelCase ) <= {
			    "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__ :      List[str]								=		make_linear_from_emb(model.model.decoder.embed_tokens )
			else:
						lowerCamelCase__ :      int								=		proj_out_weights

			model.save_pretrained(UpperCamelCase )


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

				convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)



