





import argparse
import os
from functools import reduce

import fairseq
import torch
from datasets import load_dataset

from transformers import WavaVecaProcessor, logging
from transformers.models.dataavec.configuration_dataavec_audio import DataaVecAudioConfig

# Copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_audio.py
from transformers.models.dataavec.dataavec_audio import DataaVecAudioModel as Dummy  # noqa: F401
from transformers.models.dataavec.modeling_dataavec_audio import DataaVecAudioForCTC, DataaVecAudioModel


logging.set_verbosity_info()
__lowercase													=			logging.get_logger(__name__)

__lowercase													=			{
    """post_extract_proj""": """feature_projection.projection""",
    """models.0.layer_norm""": """feature_projection.layer_norm""",
    """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""",
    """w2v_model.layer_norm""": """feature_projection.layer_norm""",
    """w2v_encoder.proj""": """lm_head""",
    """mask_emb""": """masked_spec_embed""",
}
__lowercase													=			[
    """lm_head""",
]


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Any     ,							__lowercase:		List[str]     ,							__lowercase:		List[Any]     ,							__lowercase:		Union[str, Any]     ,							__lowercase:		Optional[Any]):



  '''simple docstring'''






  for attribute in key.split('''.'''):
    __lowerCAmelCase			=				getattr(__lowercase     ,							__lowercase)

  if weight_type is not None:
    __lowerCAmelCase			=				getattr(__lowercase     ,							__lowercase).shape
  else:
    __lowerCAmelCase			=				hf_pointer.shape

  if hf_shape != value.shape:
    raise ValueError(
        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 					__SCREAMING_SNAKE_CASE  (							__lowercase:		str     ,							__lowercase:		str     ,							__lowercase:		List[str]):



  '''simple docstring'''






  __lowerCAmelCase			=				[]
  __lowerCAmelCase			=				fairseq_model.state_dict()

  if not is_headless:
    __lowerCAmelCase			=				hf_model.dataavec_audio.feature_extractor
    __lowerCAmelCase			=				hf_model.dataavec_audio.encoder.pos_conv_embed

  else:
    __lowerCAmelCase			=				hf_model.feature_extractor
    __lowerCAmelCase			=				hf_model.encoder.pos_conv_embed

  for name, value in fairseq_dict.items():
    __lowerCAmelCase			=				False
    if "conv_layers" in name:
      load_conv_layer(
          __lowercase     ,							__lowercase     ,							__lowercase     ,							__lowercase     ,							)
      __lowerCAmelCase			=				True
    elif "pos_conv" in name:
      load_pos_conv_layer(
          __lowercase     ,							__lowercase     ,							__lowercase     ,							__lowercase     ,							)
      __lowerCAmelCase			=				True
    else:
      for key, mapped_key in MAPPING.items():
        if not is_headless:
          __lowerCAmelCase			=				'''data2vec_audio.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
        if key in name or key.split('''w2v_model.''')[-1] == name.split('''.''')[0]:
          __lowerCAmelCase			=				True
          if "*" in mapped_key:
            __lowerCAmelCase			=				name.split(__lowercase)[0].split('''.''')[-2]
            __lowerCAmelCase			=				mapped_key.replace('''*'''     ,							__lowercase)
          if "weight_g" in name:
            __lowerCAmelCase			=				'''weight_g'''
          elif "weight_v" in name:
            __lowerCAmelCase			=				'''weight_v'''
          elif "bias" in name:
            __lowerCAmelCase			=				'''bias'''
          elif "weight" in name:
            # TODO: don't match quantizer.weight_proj
            __lowerCAmelCase			=				'''weight'''
          else:
            __lowerCAmelCase			=				None
          set_recursively(__lowercase     ,							__lowercase     ,							__lowercase     ,							__lowercase     ,							__lowercase)
        continue
    if not is_used:
      unused_weights.append(__lowercase)

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


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		int     ,							__lowercase:		Optional[int]):



  '''simple docstring'''






  __lowerCAmelCase			=				path.split('''.''')
  return reduce(__lowercase     ,							__lowercase     ,							__lowercase)


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Union[str, Any]     ,							__lowercase:		List[str]     ,							__lowercase:		Optional[Any]     ,							__lowercase:		Optional[int]):



  '''simple docstring'''






  __lowerCAmelCase			=				access_by_string(__lowercase     ,							__lowercase)
  __lowerCAmelCase			=				hf_weight.data

  if fsq_value.shape != hf_value.shape:
    raise ValueError(F'''{full_name} has size {fsq_value.shape}, but {hf_value.shape} was found.''')
  __lowerCAmelCase			=				fsq_value
  logger.info(F'''{full_name} was correctly initialized from {hf_weight_path}.''')


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Union[str, Any]     ,							__lowercase:		Optional[Any]     ,							__lowercase:		Dict     ,							__lowercase:		Union[str, Any]):



  '''simple docstring'''






  __lowerCAmelCase			=				full_name.split('''conv_layers.''')[-1]
  __lowerCAmelCase			=				name.split('''.''')
  __lowerCAmelCase			=				int(items[0])
  __lowerCAmelCase			=				int(items[1])

  __lowerCAmelCase			=				name.split('''.''')[-1]
  if type_id == 0:
    __lowerCAmelCase			=				'''conv'''
  elif type_id == 2:
    __lowerCAmelCase			=				'''layer_norm'''
  else:
    unused_weights.append(__lowercase)
    return

  set_weights(__lowercase     ,							__lowercase     ,							__lowercase     ,							F'''conv_layers.{layer_id}.{layer_type}.{weight_type}''')


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		int     ,							__lowercase:		List[Any]     ,							__lowercase:		List[Any]     ,							__lowercase:		Union[str, Any]):



  '''simple docstring'''






  __lowerCAmelCase			=				full_name.split('''pos_conv.''')[-1]
  __lowerCAmelCase			=				name.split('''.''')
  __lowerCAmelCase			=				int(items[0])
  __lowerCAmelCase			=				int(items[1])

  __lowerCAmelCase			=				name.split('''.''')[-1]
  if type_id != 0:
    unused_weights.append(__lowercase)
    return
  else:
    __lowerCAmelCase			=				'''conv'''

  set_weights(__lowercase     ,							__lowercase     ,							__lowercase     ,							F'''layers.{layer_id}.{layer_type}.{weight_type}''')


@torch.no_grad()
def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Optional[Any]     ,							__lowercase:		Optional[Any]     ,							__lowercase:		List[Any]=None     ,							__lowercase:		List[Any]=None     ,							__lowercase:		List[Any]=True):



  '''simple docstring'''






  if config_path is not None:
    __lowerCAmelCase			=				DataaVecAudioConfig.from_pretrained(__lowercase)
  else:
    __lowerCAmelCase			=				DataaVecAudioConfig()

  if not is_finetuned:
    # Modify final_proj layer name
    __lowerCAmelCase			=				DataaVecAudioModel(__lowercase)
    __lowerCAmelCase			=				os.path.dirname(__lowercase)

    __lowerCAmelCase			=				torch.load(__lowercase)
    __lowerCAmelCase			=				state_dict['''model'''].pop('''final_proj.0.weight''')
    __lowerCAmelCase			=				state_dict['''model'''].pop('''final_proj.0.bias''')
    __lowerCAmelCase			=				os.path.join(__lowercase     ,							'''converted.pt''')
    torch.save(__lowercase     ,							__lowercase)
  else:
    __lowerCAmelCase			=				DataaVecAudioForCTC(__lowercase)
    __lowerCAmelCase			=				checkpoint_path

  def load_dataavec(__lowercase:		Optional[Any]):
    __lowerCAmelCase	,						__lowerCAmelCase	,						__lowerCAmelCase			=				fairseq.checkpoint_utils.load_model_ensemble_and_task([path])
    return model[0].eval()

  __lowerCAmelCase			=				load_dataavec(__lowercase)

  recursively_load_weights(__lowercase     ,							__lowercase     ,							not is_finetuned)

  __lowerCAmelCase			=				WavaVecaProcessor.from_pretrained('''facebook/wav2vec2-large-lv60''')

  __lowerCAmelCase			=				load_dataset('''patrickvonplaten/librispeech_asr_dummy'''     ,							'''clean'''     ,							split='''validation''')
  __lowerCAmelCase			=				[x['''array'''] for x in ds[:4]['''audio''']]

  __lowerCAmelCase			=				processor(__lowercase     ,							return_tensors='''pt'''     ,							padding=__lowercase)

  __lowerCAmelCase			=				inputs.input_values
  __lowerCAmelCase			=				inputs.attention_mask
  #    input_values = inputs.input_values[:, :-1]
  #    attention_mask = inputs.attention_mask[:, :-1]

  hf_wavavec.eval()
  model.eval()
  if is_finetuned:
    __lowerCAmelCase			=				model(source=__lowercase     ,							padding_mask=(1 - attention_mask)     ,							mask=__lowercase     ,							features_only=__lowercase)[
        '''encoder_out'''
    ].transpose(0     ,							1)
    __lowerCAmelCase			=				hf_wavavec(__lowercase     ,							attention_mask=__lowercase)['''logits''']

    __lowerCAmelCase			=				torch.argmax(__lowercase     ,							dim=-1)
    __lowerCAmelCase			=				processor.batch_decode(__lowercase)

    print(F'''Expected Output: {ds[:4]["text"]}, Pred: {output_string}''')
  else:
    __lowerCAmelCase			=				model(source=__lowercase     ,							padding_mask=(1 - attention_mask)     ,							mask=__lowercase     ,							features_only=__lowercase)[
        '''layer_results'''
    ][-1][0].transpose(0     ,							1)
    __lowerCAmelCase			=				hf_wavavec(__lowercase     ,							attention_mask=__lowercase)['''last_hidden_state''']

  print(our_output.shape     ,							their_output.shape)
  __lowerCAmelCase			=				torch.max(torch.abs(our_output - their_output)).item()
  print(F'''max_absolute_diff = {max_absolute_diff}''')  # ~ 1e-7
  __lowerCAmelCase			=				torch.allclose(__lowercase     ,							__lowercase     ,							atol=1E-3)
  print('''Do both models output the same tensors?'''     ,							'''🔥''' if success else '''💩''')
  if not success:
    raise Exception('''Something went wRoNg''')

  hf_wavavec.save_pretrained(__lowercase)

  if is_finetuned:
    processor.save_pretrained(__lowercase)
  else:
    processor.feature_extractor.save_pretrained(__lowercase)


if __name__ == "__main__":
      __lowercase													=			argparse.ArgumentParser()
      parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
      parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""")
      parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""")
      parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
      parser.add_argument(
          """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
      )
      __lowercase													=			parser.parse_args()
      convert_wavaveca_checkpoint(
          args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
      )







import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand

class   __snake_case				(			_a   ):






    '''simple docstring'''





    @staticmethod
    def 	A		(   snake_case						:		ArgumentParser							):

      """simple docstring"""





      __lowerCAmelCase			=				parser.add_parser('''login'''			,						help='''Log in using the same credentials as on huggingface.co'''							)
      login_parser.set_defaults(func=lambda snake_case							: LoginCommand(snake_case							)							)
      __lowerCAmelCase			=				parser.add_parser('''whoami'''			,						help='''Find out which huggingface.co account you are logged in as.'''							)
      whoami_parser.set_defaults(func=lambda snake_case							: WhoamiCommand(snake_case							)							)
      __lowerCAmelCase			=				parser.add_parser('''logout'''			,						help='''Log out'''							)
      logout_parser.set_defaults(func=lambda snake_case							: LogoutCommand(snake_case							)							)

      # new system: git-based repo system
      __lowerCAmelCase			=				parser.add_parser(
          '''repo'''			,						help='''Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.'''			,						)
      __lowerCAmelCase			=				repo_parser.add_subparsers(
          help='''Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands'''							)
      __lowerCAmelCase			=				repo_subparsers.add_parser(
          '''create'''			,						help='''Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co'''							)
      repo_create_parser.add_argument(
          '''name'''			,						type=snake_case			,						help='''Name for your model\'s repo. Will be namespaced under your username to build the model id.'''			,						)
      repo_create_parser.add_argument('''--organization'''			,						type=snake_case			,						help='''Optional: organization namespace.'''							)
      repo_create_parser.add_argument('''-y'''			,						'''--yes'''			,						action='''store_true'''			,						help='''Optional: answer Yes to the prompt'''							)
      repo_create_parser.set_defaults(func=lambda snake_case							: RepoCreateCommand(snake_case							)							)


class   __snake_case				:






    '''simple docstring'''
    _lowerCAmelCase     =	"""\u001b[1m"""
    _lowerCAmelCase     =	"""\u001b[31m"""
    _lowerCAmelCase     =	"""\u001b[90m"""
    _lowerCAmelCase     =	"""\u001b[0m"""





    @classmethod
    def 	A		(   cls						:		str			,						snake_case						:		Optional[int]							):

      """simple docstring"""





      return f'''{cls._bold}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Optional[Any]			,						snake_case						:		str							):

      """simple docstring"""





      return f'''{cls._bold}{cls._red}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Dict			,						snake_case						:		List[Any]							):

      """simple docstring"""





      return f'''{cls._gray}{s}{cls._reset}'''


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		List[List[Union[str, int]]]     ,							__lowercase:		List[str]):



  '''simple docstring'''






  __lowerCAmelCase			=				[max(len(str(__lowercase)) for x in col) for col in zip(*__lowercase     ,							__lowercase)]
  __lowerCAmelCase			=				('''{{:{}}} ''' * len(__lowercase)).format(*__lowercase)
  __lowerCAmelCase			=				[]
  lines.append(row_format.format(*__lowercase))
  lines.append(row_format.format(*['''-''' * w for w in col_widths]))
  for row in rows:
    lines.append(row_format.format(*__lowercase))
  return "\n".join(__lowercase)

class   __snake_case				:






    '''simple docstring'''





    def __init__(   self						:		List[str]			,						snake_case						:		List[str]							):

      """simple docstring"""





      __lowerCAmelCase			=				args


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		List[Any]							):

      """simple docstring"""





      print(
          ANSI.red(
              '''ERROR! `huggingface-cli login` uses an outdated login mechanism '''
              '''that is not compatible with the Hugging Face Hub backend anymore. '''
              '''Please use `huggingface-cli login instead.'''							)							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		int							):

      """simple docstring"""





      print(
          ANSI.red(
              '''WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use '''
              '''`huggingface-cli whoami` instead.'''							)							)
      __lowerCAmelCase			=				HfFolder.get_token()
      if token is None:
        print('''Not logged in'''							)
        exit()
      try:
        __lowerCAmelCase	,						__lowerCAmelCase			=				whoami(snake_case							)
        print(snake_case							)
        if orgs:
          print(ANSI.bold('''orgs: '''							)			,						''','''.join(snake_case							)							)
      except HTTPError as e:
        print(snake_case							)
        print(ANSI.red(e.response.text							)							)
        exit(1							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Any							):

      """simple docstring"""





      print(
          ANSI.red(
              '''ERROR! `transformers-cli logout` uses an outdated logout mechanism '''
              '''that is not compatible with the Hugging Face Hub backend anymore. '''
              '''Please use `huggingface-cli logout instead.'''							)							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Optional[int]							):

      """simple docstring"""





      print(
          ANSI.red(
              '''WARNING! Managing repositories through transformers-cli is deprecated. '''
              '''Please use `huggingface-cli` instead.'''							)							)
      __lowerCAmelCase			=				HfFolder.get_token()
      if token is None:
        print('''Not logged in'''							)
        exit(1							)
      try:
        __lowerCAmelCase			=				subprocess.check_output(['''git''', '''--version''']							).decode('''utf-8'''							)
        print(ANSI.gray(stdout.strip()							)							)
      except FileNotFoundError:
        print('''Looks like you do not have git installed, please install.'''							)

      try:
        __lowerCAmelCase			=				subprocess.check_output(['''git-lfs''', '''--version''']							).decode('''utf-8'''							)
        print(ANSI.gray(stdout.strip()							)							)
      except FileNotFoundError:
        print(
            ANSI.red(
                '''Looks like you do not have git-lfs installed, please install.'''
                ''' You can install from https://git-lfs.github.com/.'''
                ''' Then run `git lfs install` (you only have to do this once).'''							)							)
      print(''''''							)

      __lowerCAmelCase	,						__lowerCAmelCase			=				whoami(snake_case							)
      __lowerCAmelCase			=				self.args.organization if self.args.organization is not None else user
      __lowerCAmelCase			=				f'''{namespace}/{self.args.name}'''
      print(f'''You are about to create {ANSI.bold(snake_case							)}'''							)

      if not self.args.yes:
        __lowerCAmelCase			=				input('''Proceed? [Y/n] '''							).lower()
        if not (choice == "" or choice == "y" or choice == "yes"):
          print('''Abort'''							)
          exit()
      try:
        __lowerCAmelCase			=				create_repo(snake_case			,						name=self.args.name			,						organization=self.args.organization							)
      except HTTPError as e:
        print(snake_case							)
        print(ANSI.red(e.response.text							)							)
        exit(1							)
      print('''\nYour repo now lives at:'''							)
      print(f'''  {ANSI.bold(snake_case							)}'''							)
      print('''\nYou can clone it locally with the command below, and commit/push as usual.'''							)
      print(f'''\n  git clone {url}'''							)
      print(''''''							)
