






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


snake_case__      :	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     _snake_case    (__lowercase):
   UpperCamelCase_									=     ['layers', 'blocks']
   for k in ignore_keys:
      state_dict.pop(__lowercase    ,      __lowercase)


snake_case__      :	str       	=      {
    """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     _snake_case    (__lowercase):
   UpperCamelCase_									=     list(s_dict.keys())
   for key in keys:
      UpperCamelCase_									=     key
      for k, v in WHISPER_MAPPING.items():
         if k in key:
            UpperCamelCase_									=     new_key.replace(__lowercase    ,      __lowercase)

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

      UpperCamelCase_									=     s_dict.pop(__lowercase)
   return s_dict






def     _snake_case    (__lowercase):
   UpperCamelCase_		,      UpperCamelCase_									=     emb.weight.shape
   UpperCamelCase_									=     nn.Linear(__lowercase    ,      __lowercase    ,      bias=__lowercase)
   UpperCamelCase_									=     emb.weight.data
   return lin_layer






def     _snake_case    (__lowercase    ,      __lowercase):
   os.makedirs(__lowercase    ,      exist_ok=__lowercase)
   UpperCamelCase_									=     os.path.basename(__lowercase)

   UpperCamelCase_									=     url.split('/')[-2]
   UpperCamelCase_									=     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):
      UpperCamelCase_									=     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:
            UpperCamelCase_									=     source.read(8192)
            if not buffer:
               break

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

   UpperCamelCase_									=     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     _snake_case    (__lowercase    ,      __lowercase):
   if ".pt" not in checkpoint_path:
      UpperCamelCase_									=     _download(_MODELS[checkpoint_path])
   else:
      UpperCamelCase_									=     torch.load(__lowercase    ,      map_location='cpu')
   UpperCamelCase_									=     original_checkpoint['dims']
   UpperCamelCase_									=     original_checkpoint['model_state_dict']
   UpperCamelCase_									=     state_dict['decoder.token_embedding.weight']
   remove_ignore_keys_(__lowercase)
   rename_keys(__lowercase)
   UpperCamelCase_									=     True
   UpperCamelCase_									=     state_dict['decoder.layers.0.fc1.weight'].shape[0]

   UpperCamelCase_									=     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']    ,      )

   UpperCamelCase_									=     WhisperForConditionalGeneration(__lowercase)
   UpperCamelCase_		,      UpperCamelCase_									=     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:
      UpperCamelCase_									=     make_linear_from_emb(model.model.decoder.embed_tokens)
   else:
      UpperCamelCase_									=     proj_out_weights

   model.save_pretrained(__lowercase)


if __name__ == "__main__":
 snake_case__      :	List[str]       	=      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.""")
 snake_case__      :	Tuple       	=      parser.parse_args()

 convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)













import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


snake_case__      :	str       	=      logging.getLogger(__name__)


@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None




@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None
  A_						=   None


if is_torch_available():
 import torch
 from torch.utils.data import Dataset


 class 						_a       (  UpperCAmelCase__    ):






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> Any:
      UpperCamelCase_									=     hans_processors[task]()

      UpperCamelCase_									=     os.path.join(
          _UpperCAmelCase		,		'cached_{}_{}_{}_{}'.format(
              'dev' if evaluate else 'train'		,		tokenizer.__class__.__name__		,		str(_UpperCAmelCase )		,		_UpperCAmelCase		,		)		,		)
      UpperCamelCase_									=     processor.get_labels()
      if tokenizer.__class__ in (
          RobertaTokenizer,
          RobertaTokenizerFast,
          XLMRobertaTokenizer,
          BartTokenizer,
          BartTokenizerFast,
      ):
         # HACK(label indices are swapped in RoBERTa pretrained model)
         UpperCamelCase_		,      UpperCamelCase_									=     label_list[2], label_list[1]
      UpperCamelCase_									=     label_list

      # Make sure only the first process in distributed training processes the dataset,
      # and the others will use the cache.
      UpperCamelCase_									=     cached_features_file + '.lock'
      with FileLock(_UpperCAmelCase ):
         if os.path.exists(_UpperCAmelCase ) and not overwrite_cache:
            logger.info(f"""Loading features from cached file {cached_features_file}""" )
            UpperCamelCase_									=     torch.load(_UpperCAmelCase )
         else:
            logger.info(f"""Creating features from dataset file at {data_dir}""" )

            UpperCamelCase_									=     (
                processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
            )

            logger.info('Training examples: %s'		,		len(_UpperCAmelCase ) )
            UpperCamelCase_									=     hans_convert_examples_to_features(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )
            logger.info('Saving features into cached file %s'		,		_UpperCAmelCase )
            torch.save(self.features		,		_UpperCAmelCase )




   def __len__(     self )			-> Dict:
      return len(self.features )




   def __getitem__(     self		,		_UpperCAmelCase )			-> InputFeatures:
      return self.features[i]




   def    _UpperCAmelCase     (     self )			-> Dict:
      return self.label_list


if is_tf_available():
 import tensorflow as tf


 class 						_a       :






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = 128		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> int:
      UpperCamelCase_									=     hans_processors[task]()
      UpperCamelCase_									=     processor.get_labels()
      if tokenizer.__class__ in (
          RobertaTokenizer,
          RobertaTokenizerFast,
          XLMRobertaTokenizer,
          BartTokenizer,
          BartTokenizerFast,
      ):
         # HACK(label indices are swapped in RoBERTa pretrained model)
         UpperCamelCase_		,      UpperCamelCase_									=     label_list[2], label_list[1]
      UpperCamelCase_									=     label_list

      UpperCamelCase_									=     processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
      UpperCamelCase_									=     hans_convert_examples_to_features(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )

      def gen():
         for ex_index, ex in tqdm.tqdm(enumerate(self.features )		,		desc='convert examples to features' ):
            if ex_index % 10000 == 0:
               logger.info('Writing example %d of %d' % (ex_index, len(_UpperCAmelCase )) )

            yield (
                {
                    "example_id": 0,
                    "input_ids": ex.input_ids,
                    "attention_mask": ex.attention_mask,
                    "token_type_ids": ex.token_type_ids,
                },
                ex.label,
            )

      UpperCamelCase_									=     tf.data.Dataset.from_generator(
          _UpperCAmelCase		,		(
              {
                  'example_id': tf.intaa,
                  'input_ids': tf.intaa,
                  'attention_mask': tf.intaa,
                  'token_type_ids': tf.intaa,
              },
              tf.intaa,
          )		,		(
              {
                  'example_id': tf.TensorShape([] ),
                  'input_ids': tf.TensorShape([None, None] ),
                  'attention_mask': tf.TensorShape([None, None] ),
                  'token_type_ids': tf.TensorShape([None, None] ),
              },
              tf.TensorShape([] ),
          )		,		)




   def    _UpperCAmelCase     (     self )			-> List[str]:
      return self.dataset




   def __len__(     self )			-> str:
      return len(self.features )




   def __getitem__(     self		,		_UpperCAmelCase )			-> InputFeatures:
      return self.features[i]




   def    _UpperCAmelCase     (     self )			-> int:
      return self.label_list


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Tuple:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_train_set.txt' ) )		,		'train' )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Dict:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_evaluation_set.txt' ) )		,		'dev' )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     return ["contradiction", "entailment", "neutral"]




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[str]:
     UpperCamelCase_									=     []
     for i, line in enumerate(_UpperCAmelCase ):
        if i == 0:
           continue
        UpperCamelCase_									=     '%s-%s' % (set_type, line[0])
        UpperCamelCase_									=     line[5]
        UpperCamelCase_									=     line[6]
        UpperCamelCase_									=     line[7][2:] if line[7].startswith('ex' ) else line[7]
        UpperCamelCase_									=     line[0]
        examples.append(InputExample(guid=_UpperCAmelCase		,		text_a=_UpperCAmelCase		,		text_b=_UpperCAmelCase		,		label=_UpperCAmelCase		,		pairID=_UpperCAmelCase ) )
     return examples






def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase    ,      ):
   UpperCamelCase_									=     {label: i for i, label in enumerate(__lowercase)}

   UpperCamelCase_									=     []
   for ex_index, example in tqdm.tqdm(enumerate(__lowercase)    ,      desc='convert examples to features'):
      if ex_index % 10000 == 0:
         logger.info('Writing example %d' % (ex_index))

      UpperCamelCase_									=     tokenizer(
          example.text_a    ,      example.text_b    ,      add_special_tokens=__lowercase    ,      max_length=__lowercase    ,      padding='max_length'    ,      truncation=__lowercase    ,      return_overflowing_tokens=__lowercase    ,      )

      UpperCamelCase_									=     label_map[example.label] if example.label in label_map else 0

      UpperCamelCase_									=     int(example.pairID)

      features.append(InputFeatures(**__lowercase    ,      label=__lowercase    ,      pairID=__lowercase))

   for i, example in enumerate(examples[:5]):
      logger.info('*** Example ***')
      logger.info(f"""guid: {example}""")
      logger.info(f"""features: {features[i]}""")

   return features


snake_case__      :	List[str]       	=      {
    """hans""": 3,
}

snake_case__      :	Union[str, Any]       	=      {
    """hans""": HansProcessor,
}





