
import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


lowercase__				:				Dict						=      logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
lowercase__				:				Union[str, Any]						=      direct_transformers_import(Path(__file__).parent)


lowercase__				:				Optional[int]						=      {
    "AutoTokenizer": "PreTrainedTokenizerBase",
    "AutoFeatureExtractor": "FeatureExtractionMixin",
    "AutoImageProcessor": "ImageProcessingMixin",
}






class 							SCREAMING_SNAKE_CASE__     (				SCREAMING_SNAKE_CASE_     ):

							"""simple docstring"""






							_snake_case  		=	['feature_extractor', 'tokenizer']
							# Names need to be attr_class for attr in attributes
							_snake_case  		=	None
							_snake_case  		=	None
							_snake_case  		=	None



							def __init__(	self  ,						*SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )-> str:





													'''simple docstring'''






													for key in kwargs:
																			if key not in self.attributes:
																									raise TypeError(F"Unexpected keyword argument {key}."      )
													for arg, attribute_name in zip(SCREAMING_SNAKE_CASE_  ,						self.attributes      ):
																			if attribute_name in kwargs:
																									raise TypeError(F"Got multiple values for argument {attribute_name}."      )
																			else:
																									__UpperCamelCase  	=      arg

													if len(SCREAMING_SNAKE_CASE_      ) != len(self.attributes      ):
																			raise ValueError(
																			    F"This processor requires {len(self.attributes      )} arguments: {', '.join(self.attributes      )}. Got "
																			    F"{len(SCREAMING_SNAKE_CASE_      )} arguments instead."      )

													# Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
													for attribute_name, arg in kwargs.items():
																			__UpperCamelCase  	=      getattr(self  ,						F"{attribute_name}_class"      )
																			# Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
																			__UpperCamelCase  	=      AUTO_TO_BASE_CLASS_MAPPING.get(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )
																			if isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																									__UpperCamelCase  	=      tuple(getattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ) for n in class_name if n is not None      )
																			else:
																									__UpperCamelCase  	=      getattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )

																			if not isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																									raise ValueError(
																									    F"Received a {type(SCREAMING_SNAKE_CASE_      ).__name__} for argument {attribute_name}, but a {class_name} was expected."      )

																			setattr(self  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )



							def __repr__(	self      )-> Any:





													'''simple docstring'''






													__UpperCamelCase  	=      [F"- {name}: {repr(getattr(self  ,						SCREAMING_SNAKE_CASE_      )      )}" for name in self.attributes]
													__UpperCamelCase  	=      '''\n'''.join(SCREAMING_SNAKE_CASE_      )
													return F"{self.__class__.__name__}:\n{attributes_repr}"



							def      A__		(	self  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_ = False  ,						**SCREAMING_SNAKE_CASE_      )-> List[Any]:





													'''simple docstring'''






													os.makedirs(SCREAMING_SNAKE_CASE_  ,						exist_ok=SCREAMING_SNAKE_CASE_      )

													if push_to_hub:
																			__UpperCamelCase  	=      kwargs.pop('''commit_message'''  ,						SCREAMING_SNAKE_CASE_      )
																			__UpperCamelCase  	=      kwargs.pop('''repo_id'''  ,						save_directory.split(os.path.sep      )[-1]      )
																			__UpperCamelCase  	=      self._create_repo(SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )
																			__UpperCamelCase  	=      self._get_files_timestamps(SCREAMING_SNAKE_CASE_      )
													# If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
													# loaded from the Hub.
													if self._auto_class is not None:
																			__UpperCamelCase  	=      [getattr(self  ,						SCREAMING_SNAKE_CASE_      ) for attribute_name in self.attributes]
																			__UpperCamelCase  	=      [(a.init_kwargs if isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ) else a) for a in attrs]
																			custom_object_save(self  ,						SCREAMING_SNAKE_CASE_  ,						config=SCREAMING_SNAKE_CASE_      )

													for attribute_name in self.attributes:
																			__UpperCamelCase  	=      getattr(self  ,						SCREAMING_SNAKE_CASE_      )
																			# Include the processor class in the attribute config so this processor can then be reloaded with the
																			# `AutoProcessor` API.
																			if hasattr(SCREAMING_SNAKE_CASE_  ,						'''_set_processor_class'''      ):
																									attribute._set_processor_class(self.__class__.__name__      )
																			attribute.save_pretrained(SCREAMING_SNAKE_CASE_      )

													if self._auto_class is not None:
																			# We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
																			for attribute_name in self.attributes:
																									__UpperCamelCase  	=      getattr(self  ,						SCREAMING_SNAKE_CASE_      )
																									if isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																															del attribute.init_kwargs["auto_map"]

													if push_to_hub:
																			self._upload_modified_files(
																			    SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_  ,						commit_message=SCREAMING_SNAKE_CASE_  ,						token=kwargs.get('''use_auth_token'''      )  ,						)



							@classmethod
							def      A__		(	cls  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_ = None  ,						SCREAMING_SNAKE_CASE_ = False  ,						SCREAMING_SNAKE_CASE_ = False  ,						SCREAMING_SNAKE_CASE_ = None  ,						SCREAMING_SNAKE_CASE_ = "main"  ,						**SCREAMING_SNAKE_CASE_  ,						)-> Any:





													'''simple docstring'''






													__UpperCamelCase  	=      cache_dir
													__UpperCamelCase  	=      force_download
													__UpperCamelCase  	=      local_files_only
													__UpperCamelCase  	=      revision

													__UpperCamelCase  	=      kwargs.pop('''use_auth_token'''  ,						SCREAMING_SNAKE_CASE_      )
													if use_auth_token is not None:
																			warnings.warn(
																			    '''The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.'''  ,						SCREAMING_SNAKE_CASE_      )
																			if token is not None:
																									raise ValueError(
																									    '''`token` and `use_auth_token` are both specified. Please set only the argument `token`.'''      )
																			__UpperCamelCase  	=      use_auth_token

													if token is not None:
																			# change to `token` in a follow-up PR
																			__UpperCamelCase  	=      token

													__UpperCamelCase  	=      cls._get_arguments_from_pretrained(SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )
													return cls(*SCREAMING_SNAKE_CASE_      )



							@classmethod
							def      A__		(	cls  ,						SCREAMING_SNAKE_CASE_="AutoProcessor"      )-> Optional[int]:





													'''simple docstring'''






													if not isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																			__UpperCamelCase  	=      auto_class.__name__

													import transformers.models.auto as auto_module

													if not hasattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																			raise ValueError(F"{auto_class} is not a valid auto class."      )

													__UpperCamelCase  	=      auto_class



							@classmethod
							def      A__		(	cls  ,						SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )-> Optional[int]:





													'''simple docstring'''






													__UpperCamelCase  	=      []
													for attribute_name in cls.attributes:
																			__UpperCamelCase  	=      getattr(cls  ,						F"{attribute_name}_class"      )
																			if isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																									__UpperCamelCase  	=      tuple(getattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ) if n is not None else None for n in class_name      )
																									__UpperCamelCase  	=      kwargs.get('''use_fast'''  ,						SCREAMING_SNAKE_CASE_      )
																									if use_fast and classes[1] is not None:
																															__UpperCamelCase  	=      classes[1]
																									else:
																															__UpperCamelCase  	=      classes[0]
																			else:
																									__UpperCamelCase  	=      getattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )

																			args.append(attribute_class.from_pretrained(SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )      )
													return args



							@property
							def      A__		(	self      )-> Any:





													'''simple docstring'''






													__UpperCamelCase  	=      getattr(self  ,						self.attributes[0]      )
													return getattr(SCREAMING_SNAKE_CASE_  ,						'''model_input_names'''  ,						SCREAMING_SNAKE_CASE_      )





lowercase__				:				Any						=      copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
				lowercase__				:				str						=      ProcessorMixin.push_to_hub.__doc__.format(
				    object="processor", object_class="AutoProcessor", object_files="processor files"
				)





'''simple docstring'''

import argparse

import torch
from saprl.hub import distilhubert

from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging


logging.set_verbosity_info()
lowerCAmelCase_			:			List[str]    	=   logging.get_logger(__name__)

lowerCAmelCase_			:			Optional[Any]    	=   {
    "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 __a			(						__lowerCamelCase      :    Dict			,		__lowerCamelCase      :    Optional[int]			,		__lowerCamelCase      :    str			,		__lowerCamelCase      :    int			,		__lowerCamelCase      :    Union[str, Any]					)						->				Optional[Any]:
      '''simple docstring'''


      for attribute in key.split("."					):
            lowercase_     			=   getattr(__lowerCamelCase			,		__lowerCamelCase					)

      if weight_type is not None:
            lowercase_     			=   getattr(__lowerCamelCase			,		__lowerCamelCase					).shape
      else:
            lowercase_     			=   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":
            lowercase_     			=   value
      elif weight_type == "weight_g":
            lowercase_     			=   value
      elif weight_type == "weight_v":
            lowercase_     			=   value
      elif weight_type == "bias":
            lowercase_     			=   value
      else:
            lowercase_     			=   value

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


def __a			(						__lowerCamelCase      :    List[str]			,		__lowerCamelCase      :    Optional[int]					)						->				List[Any]:
      '''simple docstring'''


      lowercase_     			=   []
      lowercase_     			=   fairseq_model.state_dict()

      lowercase_     			=   hf_model.feature_extractor

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

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

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


def __a			(						__lowerCamelCase      :    Any			,		__lowerCamelCase      :    Optional[int]			,		__lowerCamelCase      :    List[str]			,		__lowerCamelCase      :    List[str]			,		__lowerCamelCase      :    Optional[Any]					)						->				Tuple:
      '''simple docstring'''


      lowercase_     			=   full_name.split("conv_layers."					)[-1]
      lowercase_     			=   name.split("."					)
      lowercase_     			=   int(items[0]					)
      lowercase_     			=   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.'
                  )
                  lowercase_     			=   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.'
                  )
                  lowercase_     			=   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."
                  )
                  lowercase_     			=   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.'
                  )
                  lowercase_     			=   value
                  logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'					)
      else:
            unused_weights.append(__lowerCamelCase					)


def __a			(						__lowerCamelCase      :    Optional[int]					)						->				Dict:
      '''simple docstring'''


      lowercase_     			=   HubertConfig()
      lowercase_     			=   model.config

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

      return config


@torch.no_grad()
def __a			(						__lowerCamelCase      :    Optional[Any]			,		__lowerCamelCase      :    Any=None					)						->				Any:
      '''simple docstring'''


      lowercase_     			=   distilhubert().model.model

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

      lowercase_     			=   WavaVecaFeatureExtractor(
          feature_size=1			,		sampling_rate=16_000			,		padding_value=0			,		do_normalize=__lowerCamelCase			,		return_attention_mask=__lowerCamelCase			,		)
      lowercase_     			=   HubertModel(__lowerCamelCase					)

      recursively_load_weights(__lowerCamelCase			,		__lowerCamelCase					)

      feature_extractor.save_pretrained(__lowerCamelCase					)
      hf_model.save_pretrained(__lowerCamelCase					)


if __name__ == "__main__":
       lowerCAmelCase_			:			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")
       lowerCAmelCase_			:			str    	=   parser.parse_args()
       convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)






