



"""simple docstring"""





import argparse

import torch
from saprl.hub import distilhubert

from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging


logging.set_verbosity_info()
SCREAMING_SNAKE_CASE				:     str          =	logging.get_logger(__name__)

SCREAMING_SNAKE_CASE				:     List[str]          =	{
    '''post_extract_proj''': '''feature_projection.projection''',
    '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''',
    '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''',
    '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''',
    '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''',
    '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''',
    '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''',
    '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''',
    '''fc2''': '''encoder.layers.*.feed_forward.output_dense''',
    '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''',
    '''encoder.layer_norm''': '''encoder.layer_norm''',
    '''mask_emb''': '''masked_spec_embed''',
}






def 	__UpperCAmelCase					(       snake_case_  :  List[str]   ,	snake_case_  :  Dict   ,	snake_case_  :  Any   ,	snake_case_  :  str   ,	snake_case_  :  Tuple   )							->	str:






   """simple docstring"""


   for attribute in key.split("""."""   ):
      _lowerCAmelCase					     =		getattr(snake_case_   ,	snake_case_   )

   if weight_type is not None:
      _lowerCAmelCase					     =		getattr(snake_case_   ,	snake_case_   ).shape
   else:
      _lowerCAmelCase					     =		hf_pointer.shape

   assert hf_shape == value.shape, (
       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":
      _lowerCAmelCase					     =		value
   elif weight_type == "weight_g":
      _lowerCAmelCase					     =		value
   elif weight_type == "weight_v":
      _lowerCAmelCase					     =		value
   elif weight_type == "bias":
      _lowerCAmelCase					     =		value
   else:
      _lowerCAmelCase					     =		value

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






def 	__UpperCAmelCase					(       snake_case_  :  str   ,	snake_case_  :  Any   )							->	List[Any]:






   """simple docstring"""


   _lowerCAmelCase					     =		[]
   _lowerCAmelCase					     =		fairseq_model.state_dict()

   _lowerCAmelCase					     =		hf_model.feature_extractor

   for name, value in fairseq_dict.items():
      _lowerCAmelCase					     =		False
      if "conv_layers" in name:
         load_conv_layer(
             snake_case_   ,	snake_case_   ,	snake_case_   ,	snake_case_   ,	hf_model.config.feat_extract_norm == """group"""   ,	)
         _lowerCAmelCase					     =		True
      else:
         for key, mapped_key in MAPPING.items():
            _lowerCAmelCase					     =		mapped_key

            if key in name:
               _lowerCAmelCase					     =		True
               if "*" in mapped_key:
                  _lowerCAmelCase					     =		name.split(snake_case_   )[0].split("""."""   )[-2]
                  _lowerCAmelCase					     =		mapped_key.replace("""*"""   ,	snake_case_   )
               if "weight_g" in name:
                  _lowerCAmelCase					     =		"""weight_g"""
               elif "weight_v" in name:
                  _lowerCAmelCase					     =		"""weight_v"""
               elif "weight" in name:
                  _lowerCAmelCase					     =		"""weight"""
               elif "bias" in name:
                  _lowerCAmelCase					     =		"""bias"""
               else:
                  _lowerCAmelCase					     =		None
               set_recursively(snake_case_   ,	snake_case_   ,	snake_case_   ,	snake_case_   ,	snake_case_   )
            continue
      if not is_used:
         unused_weights.append(snake_case_   )

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






def 	__UpperCAmelCase					(       snake_case_  :  Any   ,	snake_case_  :  List[Any]   ,	snake_case_  :  Dict   ,	snake_case_  :  Union[str, Any]   ,	snake_case_  :  Optional[Any]   )							->	List[Any]:






   """simple docstring"""


   _lowerCAmelCase					     =		full_name.split("""conv_layers."""   )[-1]
   _lowerCAmelCase					     =		name.split("""."""   )
   _lowerCAmelCase					     =		int(items[0]   )
   _lowerCAmelCase					     =		int(items[1]   )

   if type_id == 0:
      if "bias" in name:
         assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
             F"""{full_name} has size {value.shape}, but"""
             F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."""
         )
         _lowerCAmelCase					     =		value
         logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}."""   )
      elif "weight" in name:
         assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
             F"""{full_name} has size {value.shape}, but"""
             F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."""
         )
         _lowerCAmelCase					     =		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:
         assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
             F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"""
             " found."
         )
         _lowerCAmelCase					     =		value
         logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""   )
      elif "weight" in name:
         assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
             F"""{full_name} has size {value.shape}, but"""
             F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."""
         )
         _lowerCAmelCase					     =		value
         logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""   )
   else:
      unused_weights.append(snake_case_   )






def 	__UpperCAmelCase					(       snake_case_  :  Optional[int]   )							->	Any:






   """simple docstring"""


   _lowerCAmelCase					     =		HubertConfig()
   _lowerCAmelCase					     =		model.config

   _lowerCAmelCase					     =		fs_config.activation_dropout
   _lowerCAmelCase					     =		False
   _lowerCAmelCase					     =		fs_config.attention_dropout
   _lowerCAmelCase					     =		False
   _lowerCAmelCase					     =		eval(fs_config.extractor_conv_feature_layers   )
   _lowerCAmelCase					     =		[x[0] for x in conv_layers]
   _lowerCAmelCase					     =		[x[1] for x in conv_layers]
   _lowerCAmelCase					     =		[x[2] for x in conv_layers]
   _lowerCAmelCase					     =		"""gelu"""
   _lowerCAmelCase					     =		"""layer""" if fs_config.extractor_mode == """layer_norm""" else """group"""
   _lowerCAmelCase					     =		False
   _lowerCAmelCase					     =		0.0
   _lowerCAmelCase					     =		0.0
   _lowerCAmelCase					     =		fs_config.activation_fn
   _lowerCAmelCase					     =		fs_config.dropout
   _lowerCAmelCase					     =		fs_config.encoder_embed_dim
   _lowerCAmelCase					     =		0.0_2
   _lowerCAmelCase					     =		fs_config.encoder_ffn_embed_dim
   _lowerCAmelCase					     =		1e-5
   _lowerCAmelCase					     =		0.0
   _lowerCAmelCase					     =		fs_config.encoder_attention_heads
   _lowerCAmelCase					     =		fs_config.conv_pos_groups
   _lowerCAmelCase					     =		fs_config.conv_pos
   _lowerCAmelCase					     =		len(snake_case_   )
   _lowerCAmelCase					     =		fs_config.encoder_layers

   return config






@torch.no_grad()
def 	__UpperCAmelCase					(       snake_case_  :  Optional[Any]   ,	snake_case_  :  Union[str, Any]=None   )							->	List[str]:






   """simple docstring"""


   _lowerCAmelCase					     =		distilhubert().model.model

   if config_path is not None:
      _lowerCAmelCase					     =		HubertConfig.from_pretrained(snake_case_   )
   else:
      _lowerCAmelCase					     =		convert_config(snake_case_   )
   _lowerCAmelCase					     =		model.eval()

   _lowerCAmelCase					     =		WavaVecaFeatureExtractor(
       feature_size=1   ,	sampling_rate=16000   ,	padding_value=0   ,	do_normalize=snake_case_   ,	return_attention_mask=snake_case_   ,	)
   _lowerCAmelCase					     =		HubertModel(snake_case_   )

   recursively_load_weights(snake_case_   ,	snake_case_   )

   feature_extractor.save_pretrained(snake_case_   )
   hf_model.save_pretrained(snake_case_   )


if __name__ == "__main__":
  SCREAMING_SNAKE_CASE				:     List[str]          =	argparse.ArgumentParser()
  parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
  parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
  SCREAMING_SNAKE_CASE				:     Optional[int]          =	parser.parse_args()
  convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)




"""simple docstring"""





import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


SCREAMING_SNAKE_CASE				:     Optional[Any]          =	logging.get_logger(__name__)


SCREAMING_SNAKE_CASE				:     int          =	{'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''}

# See all MVP models at https://huggingface.co/models?filter=mvp
SCREAMING_SNAKE_CASE				:     Union[str, Any]          =	{
    '''vocab_file''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json''',
    },
    '''added_tokens.json''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json''',
    },
    '''merges_file''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt''',
    },
}

SCREAMING_SNAKE_CASE				:     Union[str, Any]          =	{
    '''RUCAIBox/mvp''': 1_0_2_4,
}






@lru_cache()
def 	__UpperCAmelCase					(       )							->	Tuple:






   """simple docstring"""


   _lowerCAmelCase					     =		(
       list(range(ord("""!"""   )   ,	ord("""~"""   ) + 1   )   ) + list(range(ord("""¡"""   )   ,	ord("""¬"""   ) + 1   )   ) + list(range(ord("""®"""   )   ,	ord("""ÿ"""   ) + 1   )   )
   )
   _lowerCAmelCase					     =		bs[:]
   _lowerCAmelCase					     =		0
   for b in range(2**8   ):
      if b not in bs:
         bs.append(snake_case_   )
         cs.append(2**8 + n   )
         n += 1
   _lowerCAmelCase					     =		[chr(snake_case_   ) for n in cs]
   return dict(zip(snake_case_   ,	snake_case_   )   )






def 	__UpperCAmelCase					(       snake_case_  :  Dict   )							->	List[Any]:






   """simple docstring"""


   _lowerCAmelCase					     =		set()
   _lowerCAmelCase					     =		word[0]
   for char in word[1:]:
      pairs.add((prev_char, char)   )
      _lowerCAmelCase					     =		char
   return pairs



class       __lowerCamelCase	(   __lowercase    ):
   __UpperCamelCase									=   VOCAB_FILES_NAMES
   __UpperCamelCase									=   PRETRAINED_VOCAB_FILES_MAP
   __UpperCamelCase									=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __UpperCamelCase									=   ['input_ids', 'attention_mask']







   def __init__(self       ,	lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase="replace"       ,	lowerCamelCase="<s>"       ,	lowerCamelCase="</s>"       ,	lowerCamelCase="</s>"       ,	lowerCamelCase="<s>"       ,	lowerCamelCase="<unk>"       ,	lowerCamelCase="<pad>"       ,	lowerCamelCase="<mask>"       ,	lowerCamelCase=False       ,	**lowerCamelCase       ,	):




      '''simple docstring'''




      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else bos_token
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else eos_token
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else sep_token
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else cls_token
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else unk_token
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else pad_token

      # Mask token behave like a normal word, i.e. include the space before it
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else mask_token

      super().__init__(
          errors=lowerCamelCase       ,	bos_token=lowerCamelCase       ,	eos_token=lowerCamelCase       ,	unk_token=lowerCamelCase       ,	sep_token=lowerCamelCase       ,	cls_token=lowerCamelCase       ,	pad_token=lowerCamelCase       ,	mask_token=lowerCamelCase       ,	add_prefix_space=lowerCamelCase       ,	**lowerCamelCase       ,	)
      with open(lowerCamelCase       ,	encoding="""utf-8"""				) as vocab_handle:
         _lowerCAmelCase					     =		json.load(lowerCamelCase				)
      _lowerCAmelCase					     =		{v: k for k, v in self.encoder.items()}
      _lowerCAmelCase					     =		errors  # how to handle errors in decoding
      _lowerCAmelCase					     =		bytes_to_unicode()
      _lowerCAmelCase					     =		{v: k for k, v in self.byte_encoder.items()}
      with open(lowerCamelCase       ,	encoding="""utf-8"""				) as merges_handle:
         _lowerCAmelCase					     =		merges_handle.read().split("""\n"""				)[1:-1]
      _lowerCAmelCase					     =		[tuple(merge.split()				) for merge in bpe_merges]
      _lowerCAmelCase					     =		dict(zip(lowerCamelCase       ,	range(len(lowerCamelCase				)				)				)				)
      _lowerCAmelCase					     =		{}
      _lowerCAmelCase					     =		add_prefix_space

      # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
      _lowerCAmelCase					     =		re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""				)







   @property
   def 							A__						(self				):




      '''simple docstring'''




      return len(self.encoder				)







   def 							A__						(self				):




      '''simple docstring'''




      return dict(self.encoder       ,	**self.added_tokens_encoder				)







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      if token in self.cache:
         return self.cache[token]
      _lowerCAmelCase					     =		tuple(lowerCamelCase				)
      _lowerCAmelCase					     =		get_pairs(lowerCamelCase				)

      if not pairs:
         return token

      while True:
         _lowerCAmelCase					     =		min(lowerCamelCase       ,	key=lambda lowerCamelCase				: self.bpe_ranks.get(lowerCamelCase       ,	float("""inf"""				)				)				)
         if bigram not in self.bpe_ranks:
            break
         _lowerCAmelCase     ,						_lowerCAmelCase					     =		bigram
         _lowerCAmelCase					     =		[]
         _lowerCAmelCase					     =		0
         while i < len(lowerCamelCase				):
            try:
               _lowerCAmelCase					     =		word.index(lowerCamelCase       ,	lowerCamelCase				)
            except ValueError:
               new_word.extend(word[i:]				)
               break
            else:
               new_word.extend(word[i:j]				)
               _lowerCAmelCase					     =		j

            if word[i] == first and i < len(lowerCamelCase				) - 1 and word[i + 1] == second:
               new_word.append(first + second				)
               i += 2
            else:
               new_word.append(word[i]				)
               i += 1
         _lowerCAmelCase					     =		tuple(lowerCamelCase				)
         _lowerCAmelCase					     =		new_word
         if len(lowerCamelCase				) == 1:
            break
         else:
            _lowerCAmelCase					     =		get_pairs(lowerCamelCase				)
      _lowerCAmelCase					     =		""" """.join(lowerCamelCase				)
      _lowerCAmelCase					     =		word
      return word







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		[]
      for token in re.findall(self.pat       ,	lowerCamelCase				):
         _lowerCAmelCase					     =		"""""".join(
             self.byte_encoder[b] for b in token.encode("""utf-8"""				)				)  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
         bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCamelCase				).split(""" """				)				)
      return bpe_tokens







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      return self.encoder.get(lowerCamelCase       ,	self.encoder.get(self.unk_token				)				)







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      return self.decoder.get(lowerCamelCase				)







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		"""""".join(lowerCamelCase				)
      _lowerCAmelCase					     =		bytearray([self.byte_decoder[c] for c in text]				).decode("""utf-8"""       ,	errors=self.errors				)
      return text







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None				):




      '''simple docstring'''




      if not os.path.isdir(lowerCamelCase				):
         logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""				)
         return
      _lowerCAmelCase					     =		os.path.join(
          lowerCamelCase       ,	(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]				)
      _lowerCAmelCase					     =		os.path.join(
          lowerCamelCase       ,	(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]				)

      with open(lowerCamelCase       ,	"""w"""       ,	encoding="""utf-8"""				) as f:
         f.write(json.dumps(self.encoder       ,	indent=2       ,	sort_keys=lowerCamelCase       ,	ensure_ascii=lowerCamelCase				) + """\n"""				)

      _lowerCAmelCase					     =		0
      with open(lowerCamelCase       ,	"""w"""       ,	encoding="""utf-8"""				) as writer:
         writer.write("""#version: 0.2\n"""				)
         for bpe_tokens, token_index in sorted(self.bpe_ranks.items()       ,	key=lambda lowerCamelCase				: kv[1]				):
            if index != token_index:
               logger.warning(
                   f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
                   """ Please check that the tokenizer is not corrupted!"""				)
               _lowerCAmelCase					     =		token_index
            writer.write(""" """.join(lowerCamelCase				) + """\n"""				)
            index += 1

      return vocab_file, merge_file







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None				):




      '''simple docstring'''




      if token_ids_a is None:
         return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      _lowerCAmelCase					     =		[self.cls_token_id]
      _lowerCAmelCase					     =		[self.sep_token_id]
      return cls + token_ids_a + sep + sep + token_ids_a + sep







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None       ,	lowerCamelCase = False				):




      '''simple docstring'''




      if already_has_special_tokens:
         return super().get_special_tokens_mask(
             token_ids_a=lowerCamelCase       ,	token_ids_a=lowerCamelCase       ,	already_has_special_tokens=lowerCamelCase				)

      if token_ids_a is None:
         return [1] + ([0] * len(lowerCamelCase				)) + [1]
      return [1] + ([0] * len(lowerCamelCase				)) + [1, 1] + ([0] * len(lowerCamelCase				)) + [1]







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None				):




      '''simple docstring'''




      _lowerCAmelCase					     =		[self.sep_token_id]
      _lowerCAmelCase					     =		[self.cls_token_id]

      if token_ids_a is None:
         return len(cls + token_ids_a + sep				) * [0]
      return len(cls + token_ids_a + sep + sep + token_ids_a + sep				) * [0]







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase=False       ,	**lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		kwargs.pop("""add_prefix_space"""       ,	self.add_prefix_space				)
      if (is_split_into_words or add_prefix_space) and (len(lowerCamelCase				) > 0 and not text[0].isspace()):
         _lowerCAmelCase					     =		""" """ + text
      return (text, kwargs)