import os
from pathlib import Path

import numpy as np
import pytest
from pack_dataset import pack_data_dir
from parameterized import parameterized
from save_len_file import save_len_file
from torch.utils.data import DataLoader

from transformers import AutoTokenizer
from transformers.models.mbart.modeling_mbart import shift_tokens_right
from transformers.testing_utils import TestCasePlus, slow
from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset


__lowercase										= '''bert-base-cased'''
__lowercase										= '''google/pegasus-xsum'''
__lowercase										= [''' Sam ate lunch today.''', '''Sams lunch ingredients.''']
__lowercase										= ['''A very interesting story about what I ate for lunch.''', '''Avocado, celery, turkey, coffee''']
__lowercase										= '''patrickvonplaten/t5-tiny-random'''
__lowercase										= '''sshleifer/bart-tiny-random'''
__lowercase										= '''sshleifer/tiny-mbart'''
__lowercase										= '''sshleifer/tiny-marian-en-de'''



def lowerCamelCase  (       SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    __UpperCamelCase					:str        =		'''\n'''.join(SCREAMING_SNAKE_CASE     )
    Path(SCREAMING_SNAKE_CASE     ).open('''w'''     ).writelines(SCREAMING_SNAKE_CASE     )



def lowerCamelCase  (       SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    for split in ["train", "val", "test"]:
        _dump_articles(os.path.join(SCREAMING_SNAKE_CASE  ,      f"""{split}.source"""     )  ,      SCREAMING_SNAKE_CASE     )
        _dump_articles(os.path.join(SCREAMING_SNAKE_CASE  ,      f"""{split}.target"""     )  ,      SCREAMING_SNAKE_CASE     )
    return tmp_dir


class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    @parameterized.expand(
        [
            MBART_TINY,
            MARIAN_TINY,
            T5_TINY,
            BART_TINY,
            PEGASUS_XSUM,
        ]			,			)
    @slow
    def       UpperCamelCase__       (     self			,			__lowercase)	->     List[Any]:
        __UpperCamelCase					:Dict        =		AutoTokenizer.from_pretrained(__lowercase)
        __UpperCamelCase					:Optional[Any]        =		make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())
        __UpperCamelCase					:List[Any]        =		max(len(tokenizer.encode(__lowercase)) for a in ARTICLES)
        __UpperCamelCase					:Optional[int]        =		max(len(tokenizer.encode(__lowercase)) for a in SUMMARIES)
        __UpperCamelCase					:int        =		4
        __UpperCamelCase					:Any        =		8
        assert max_len_target > max_src_len  # Will be truncated
        assert max_len_source > max_src_len  # Will be truncated
        __UpperCamelCase					:Tuple        =		'''ro_RO''', '''de_DE'''  # ignored for all but mbart, but never causes error.
        __UpperCamelCase					:str        =		SeqaSeqDataset(
            __lowercase			,			data_dir=__lowercase			,			type_path='''train'''			,			max_source_length=__lowercase			,			max_target_length=__lowercase			,			src_lang=__lowercase			,			tgt_lang=__lowercase			,			)
        __UpperCamelCase					:Any        =		DataLoader(__lowercase			,			batch_size=2			,			collate_fn=train_dataset.collate_fn)
        for batch in dataloader:
            assert isinstance(__lowercase			,			__lowercase)
            assert batch["attention_mask"].shape == batch["input_ids"].shape
            # show that articles were trimmed.
            assert batch["input_ids"].shape[1] == max_src_len
            # show that targets are the same len
            assert batch["labels"].shape[1] == max_tgt_len
            if tok_name != MBART_TINY:
                continue
            # check language codes in correct place
            __UpperCamelCase					:Optional[int]        =		shift_tokens_right(batch['''labels''']			,			tokenizer.pad_token_id)
            assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang]
            assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id
            assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id
            assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang]

            break  # No need to test every batch







    @parameterized.expand([BART_TINY, BERT_BASE_CASED])
    def       UpperCamelCase__       (     self			,			__lowercase)	->     int:
        __UpperCamelCase					:Union[str, Any]        =		AutoTokenizer.from_pretrained(__lowercase)
        __UpperCamelCase					:Union[str, Any]        =		make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())
        __UpperCamelCase					:int        =		max(len(tokenizer.encode(__lowercase)) for a in ARTICLES)
        __UpperCamelCase					:Dict        =		max(len(tokenizer.encode(__lowercase)) for a in SUMMARIES)
        __UpperCamelCase					:Union[str, Any]        =		4
        __UpperCamelCase					:List[str]        =		LegacySeqaSeqDataset(
            __lowercase			,			data_dir=__lowercase			,			type_path='''train'''			,			max_source_length=20			,			max_target_length=__lowercase			,			)
        __UpperCamelCase					:Dict        =		DataLoader(__lowercase			,			batch_size=2			,			collate_fn=train_dataset.collate_fn)
        for batch in dataloader:
            assert batch["attention_mask"].shape == batch["input_ids"].shape
            # show that articles were trimmed.
            assert batch["input_ids"].shape[1] == max_len_source
            assert 20 >= batch["input_ids"].shape[1]  # trimmed significantly
            # show that targets were truncated
            assert batch["labels"].shape[1] == trunc_target  # Truncated
            assert max_len_target > trunc_target  # Truncated
            break  # No need to test every batch







    def       UpperCamelCase__       (     self)	->     Dict:
        __UpperCamelCase					:List[Any]        =		AutoTokenizer.from_pretrained('''facebook/mbart-large-cc25''')

        __UpperCamelCase					:Union[str, Any]        =		Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()))
        __UpperCamelCase					:str        =		tmp_dir.joinpath('''train.source''').open().readlines()
        __UpperCamelCase					:int        =		Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()))
        pack_data_dir(__lowercase			,			__lowercase			,			128			,			__lowercase)
        __UpperCamelCase					:Union[str, Any]        =		{x.name for x in tmp_dir.iterdir()}
        __UpperCamelCase					:int        =		{x.name for x in save_dir.iterdir()}
        __UpperCamelCase					:Optional[int]        =		save_dir.joinpath('''train.source''').open().readlines()
        # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.']
        # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.']
        assert len(__lowercase) < len(__lowercase)
        assert len(__lowercase) == 1
        assert len(packed_examples[0]) == sum(len(__lowercase) for x in orig_examples)
        assert orig_paths == new_paths







    @pytest.mark.skipif(not FAIRSEQ_AVAILABLE			,			reason='''This test requires fairseq''')
    def       UpperCamelCase__       (     self)	->     List[Any]:
        if not FAIRSEQ_AVAILABLE:
            return
        __UpperCamelCase					:Any        =		self._get_dataset(max_len=64)
        __UpperCamelCase					:Union[str, Any]        =		64
        __UpperCamelCase					:Tuple        =		ds.make_dynamic_sampler(__lowercase			,			required_batch_size_multiple=__lowercase)
        __UpperCamelCase					:List[str]        =		[len(__lowercase) for x in batch_sampler]
        assert len(set(__lowercase)) > 1  # it's not dynamic batch size if every batch is the same length
        assert sum(__lowercase) == len(__lowercase)  # no dropped or added examples
        __UpperCamelCase					:int        =		DataLoader(__lowercase			,			batch_sampler=__lowercase			,			collate_fn=ds.collate_fn			,			num_workers=2)
        __UpperCamelCase					:List[str]        =		[]
        __UpperCamelCase					:int        =		[]
        for batch in data_loader:
            __UpperCamelCase					:List[Any]        =		batch['''input_ids'''].shape
            __UpperCamelCase					:Dict        =		src_shape[0]
            assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple
            __UpperCamelCase					:Optional[int]        =		np.product(batch['''input_ids'''].shape)
            num_src_per_batch.append(__lowercase)
            if num_src_tokens > (max_tokens * 1.1):
                failures.append(__lowercase)
        assert num_src_per_batch[0] == max(__lowercase)
        if failures:
            raise AssertionError(f"""too many tokens in {len(__lowercase)} batches""")







    def       UpperCamelCase__       (     self)	->     Tuple:
        __UpperCamelCase					:Optional[Any]        =		self._get_dataset(max_len=512)
        __UpperCamelCase					:Any        =		2
        __UpperCamelCase					:List[Any]        =		ds.make_sortish_sampler(__lowercase			,			shuffle=__lowercase)

        __UpperCamelCase					:List[Any]        =		DataLoader(__lowercase			,			batch_size=__lowercase			,			collate_fn=ds.collate_fn			,			num_workers=2)
        __UpperCamelCase					:Tuple        =		DataLoader(__lowercase			,			batch_size=__lowercase			,			collate_fn=ds.collate_fn			,			num_workers=2			,			sampler=__lowercase)

        __UpperCamelCase					:int        =		tokenizer.pad_token_id

        def count_pad_tokens(__lowercase			,			__lowercase="input_ids"):
            return [batch[k].eq(__lowercase).sum().item() for batch in data_loader]

        assert sum(count_pad_tokens(__lowercase			,			k='''labels''')) < sum(count_pad_tokens(__lowercase			,			k='''labels'''))
        assert sum(count_pad_tokens(__lowercase)) < sum(count_pad_tokens(__lowercase))
        assert len(__lowercase) == len(__lowercase)







    def       UpperCamelCase__       (     self			,			__lowercase=1_000			,			__lowercase=128)	->     List[Any]:
        if os.getenv('''USE_REAL_DATA'''			,			__lowercase):
            __UpperCamelCase					:Optional[Any]        =		'''examples/seq2seq/wmt_en_ro'''
            __UpperCamelCase					:Dict        =		max_len * 2 * 64
            if not Path(__lowercase).joinpath('''train.len''').exists():
                save_len_file(__lowercase			,			__lowercase)
        else:
            __UpperCamelCase					:Union[str, Any]        =		'''examples/seq2seq/test_data/wmt_en_ro'''
            __UpperCamelCase					:Optional[int]        =		max_len * 4
            save_len_file(__lowercase			,			__lowercase)

        __UpperCamelCase					:str        =		AutoTokenizer.from_pretrained(__lowercase)
        __UpperCamelCase					:List[Any]        =		SeqaSeqDataset(
            __lowercase			,			data_dir=__lowercase			,			type_path='''train'''			,			max_source_length=__lowercase			,			max_target_length=__lowercase			,			n_obs=__lowercase			,			)
        return ds, max_tokens, tokenizer







    def       UpperCamelCase__       (     self)	->     Tuple:
        __UpperCamelCase					:List[Any]        =		self._get_dataset()
        __UpperCamelCase					:List[str]        =		set(DistributedSortishSampler(__lowercase			,			256			,			num_replicas=2			,			rank=0			,			add_extra_examples=__lowercase))
        __UpperCamelCase					:Tuple        =		set(DistributedSortishSampler(__lowercase			,			256			,			num_replicas=2			,			rank=1			,			add_extra_examples=__lowercase))
        assert idsa.intersection(__lowercase) == set()







    @parameterized.expand(
        [
            MBART_TINY,
            MARIAN_TINY,
            T5_TINY,
            BART_TINY,
            PEGASUS_XSUM,
        ]			,			)
    def       UpperCamelCase__       (     self			,			__lowercase)	->     List[Any]:
        __UpperCamelCase					:List[Any]        =		AutoTokenizer.from_pretrained(__lowercase			,			use_fast=__lowercase)
        if tok_name == MBART_TINY:
            __UpperCamelCase					:Optional[Any]        =		SeqaSeqDataset(
                __lowercase			,			data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())			,			type_path='''train'''			,			max_source_length=4			,			max_target_length=8			,			src_lang='''EN'''			,			tgt_lang='''FR'''			,			)
            __UpperCamelCase					:Tuple        =		train_dataset.dataset_kwargs
            assert "src_lang" in kwargs and "tgt_lang" in kwargs
        else:
            __UpperCamelCase					:Tuple        =		SeqaSeqDataset(
                __lowercase			,			data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())			,			type_path='''train'''			,			max_source_length=4			,			max_target_length=8			,			)
            __UpperCamelCase					:Optional[int]        =		train_dataset.dataset_kwargs
            assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs
            assert len(__lowercase) == 1 if tok_name == BART_TINY else len(__lowercase) == 0




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 lowerCamelCase  (       SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







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


__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 lowerCamelCase  (       SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







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

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

        __UpperCamelCase					:Any        =		s_dict.pop(SCREAMING_SNAKE_CASE     )
    return s_dict



def lowerCamelCase  (       SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







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



def lowerCamelCase  (       SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    os.makedirs(SCREAMING_SNAKE_CASE  ,      exist_ok=SCREAMING_SNAKE_CASE     )
    __UpperCamelCase					:int        =		os.path.basename(SCREAMING_SNAKE_CASE     )

    __UpperCamelCase					:Optional[Any]        =		url.split('''/'''     )[-2]
    __UpperCamelCase					:Tuple        =		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     ):
        __UpperCamelCase					:List[str]        =		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=1_024     ) as loop:
            while True:
                __UpperCamelCase					:Optional[Any]        =		source.read(8_192     )
                if not buffer:
                    break

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

    __UpperCamelCase					:str        =		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  ,      SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







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

    __UpperCamelCase					:Dict        =		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''']  ,      )

    __UpperCamelCase					:str        =		WhisperForConditionalGeneration(SCREAMING_SNAKE_CASE     )
    __UpperCamelCase  ,	__UpperCamelCase					: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:
        __UpperCamelCase					:Optional[Any]        =		make_linear_from_emb(model.model.decoder.embed_tokens     )
    else:
        __UpperCamelCase					:Union[str, Any]        =		proj_out_weights

    model.save_pretrained(SCREAMING_SNAKE_CASE     )


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)





