



'''simple docstring'''






import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    UniSpeechConfig,
    UniSpeechForCTC,
    UniSpeechForPreTraining,
    WavaVecaFeatureExtractor,
    WavaVecaPhonemeCTCTokenizer,
    WavaVecaProcessor,
    logging,
)


logging.set_verbosity_info()
lowerCAmelCase:      List[Any]		 =		logging.get_logger(__name__)

lowerCAmelCase:      List[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',
    'w2v_model.layer_norm': 'feature_projection.layer_norm',
    'quantizer.weight_proj': 'quantizer.weight_proj',
    'quantizer.vars': 'quantizer.codevectors',
    'project_q': 'project_q',
    'final_proj': 'project_hid',
    'w2v_encoder.proj': 'ctc_proj',
    'mask_emb': 'masked_spec_embed',
}
lowerCAmelCase:      List[str]		 =		[
    'ctc_proj',
    'quantizer.weight_proj',
    'quantizer.codevectors',
    'project_q',
    'project_hid',
]
def    lowerCamelCase__ (		_A				,    _A				,    _A				,    _A				,    _A				,    _A       ):
  for attribute in key.split('.'       ):
    if is_finetuned:
      if attribute in ["quantizer", "project_q", "project_hid"]:
        # those layers are only relevant for pretraining and should be dropped
        return

      if attribute == "ctc_proj":
        # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
        a		:      List[str]       =  'lm_head'

    a		:      Dict       =  getattr(_A				,    _A       )

  if weight_type is not None:
    a		:      Union[str, Any]       =  getattr(_A				,    _A       ).shape
  else:
    a		:      Optional[int]       =  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":
    a		:      int       =  value
  elif weight_type == "weight_g":
    a		:      Dict       =  value
  elif weight_type == "weight_v":
    a		:      Any       =  value
  elif weight_type == "bias":
    a		:      Dict       =  value
  else:
    a		:      Optional[Any]       =  value

  logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}."""       )
def    lowerCamelCase__ (		_A				,    _A				,    _A       ):
  a		:      Optional[int]       =  []
  a		:      Dict       =  fairseq_model.state_dict()

  a		:      Union[str, Any]       =  hf_model.unispeech.feature_extractor

  for name, value in fairseq_dict.items():
    a		:      str       =  False
    if "conv_layers" in name:
      load_conv_layer(
          _A				,    _A				,    _A				,    _A				,    hf_model.config.feat_extract_norm == 'group'				,    )
      a		:      Dict       =  True
    else:
      for key, mapped_key in MAPPING.items():
        a		:      Any       =  'unispeech.' + 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]:
          a		:      Optional[Any]       =  True
          if "*" in mapped_key:
            a		:      Tuple       =  name.split(_A       )[0].split('.'       )[-2]
            a		:      Union[str, Any]       =  mapped_key.replace('*'				,    _A       )
          if "weight_g" in name:
            a		:      str       =  'weight_g'
          elif "weight_v" in name:
            a		:      List[Any]       =  'weight_v'
          elif "bias" in name:
            a		:      List[str]       =  'bias'
          elif "weight" in name:
            # TODO: don't match quantizer.weight_proj
            a		:      List[Any]       =  'weight'
          else:
            a		:      int       =  None
          set_recursively(_A				,    _A				,    _A				,    _A				,    _A				,    _A       )
        continue
    if not is_used:
      unused_weights.append(_A       )

  logger.warning(f"""Unused weights: {unused_weights}"""       )
def    lowerCamelCase__ (		_A				,    _A				,    _A				,    _A				,    _A       ):
  a		:      Optional[int]       =  full_name.split('conv_layers.'       )[-1]
  a		:      int       =  name.split('.'       )
  a		:      int       =  int(items[0]       )
  a		:      str       =  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."""
      )
      a		:      int       =  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."""
      )
      a		:      int       =  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."
      )
      a		:      Any       =  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."""
      )
      a		:      Any       =  value
      logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""       )
  else:
    unused_weights.append(_A       )
@torch.no_grad()
def    lowerCamelCase__ (		_A				,    _A				,    _A=None				,    _A=None				,    _A=True       ):
  if config_path is not None:
    a		:      Any       =  UniSpeechConfig.from_pretrained(_A       )
  else:
    a		:      List[Any]       =  UniSpeechConfig()

  if is_finetuned:
    if dict_path:
      a		:      Tuple       =  Dictionary.load_from_json(_A       )

      # important change bos & pad token id since CTC symbol is <pad> and
      # not <s> as in fairseq
      a		:      Dict       =  target_dict.pad_index
      a		:      str       =  target_dict.bos_index
      a		:      Tuple       =  target_dict.eos_index
      a		:      Any       =  len(target_dict.symbols       )
      a		:      Union[str, Any]       =  os.path.join(_A				,    'vocab.json'       )
      if not os.path.isdir(_A       ):
        logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(_A       )       )
        return
      os.makedirs(_A				,    exist_ok=_A       )
      a		:      Optional[int]       =  target_dict.indices

      # fairseq has the <pad> and <s> switched
      a		:      str       =  42
      a		:      Any       =  43
      with open(_A				,    'w'				,    encoding='utf-8'       ) as vocab_handle:
        json.dump(_A				,    _A       )
      a		:      List[str]       =  WavaVecaPhonemeCTCTokenizer(
          _A				,    unk_token=target_dict.unk_word				,    pad_token=target_dict.pad_word				,    bos_token=target_dict.bos_word				,    eos_token=target_dict.eos_word				,    word_delimiter_token='|'				,    do_lower_case=_A				,    )
      a		:      Union[str, Any]       =  True if config.feat_extract_norm == 'layer' else False
      a		:      str       =  WavaVecaFeatureExtractor(
          feature_size=1				,    sampling_rate=1_6000				,    padding_value=0				,    do_normalize=_A				,    return_attention_mask=_A				,    )
      a		:      int       =  WavaVecaProcessor(feature_extractor=_A				,    tokenizer=_A       )
      processor.save_pretrained(_A       )

    a		:      List[str]       =  UniSpeechForCTC(_A       )
  else:
    a		:      List[str]       =  UniSpeechForPreTraining(_A       )

  if is_finetuned:
    a     ,			a     ,			a		:      Any       =  fairseq.checkpoint_utils.load_model_ensemble_and_task(
        [checkpoint_path]				,    arg_overrides={'data': '/'.join(dict_path.split('/'       )[:-1]       ), 'w2v_path': checkpoint_path}       )
  else:
    a     ,			a     ,			a		:      Optional[int]       =  fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]       )

  a		:      int       =  model[0].eval()

  recursively_load_weights(_A				,    _A				,    _A       )

  hf_unispeech.save_pretrained(_A       )


if __name__ == "__main__":
     lowerCAmelCase:      Any		 =		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'
     )
     lowerCAmelCase:      int		 =		parser.parse_args()
     convert_unispeech_checkpoint(
         args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
     )




'''simple docstring'''






from collections import UserDict
from typing import Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


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

@add_end_docstrings(lowerCamelCase__			)
class 							a__(      lowerCamelCase__			):







    def __init__(   self				:						Union[str, Any]		,    **__snake_case				:						List[str]			):
      super().__init__(**__snake_case			)

      if self.framework != "pt":
        raise ValueError(F"""The {self.__class__} is only available in PyTorch."""			)
      # No specific FOR_XXX available yet







    def __call__(   self				:						Any		,    __snake_case				:						Union[np.ndarray, bytes, str]		,    **__snake_case				:						Optional[Any]			):
      return super().__call__(__snake_case		,    **__snake_case			)







    def     lowercase_ (   self				:						Dict		,    **__snake_case				:						Optional[int]			):
      a		:      str       =  {}
      if "candidate_labels" in kwargs:
        a		:      Optional[int]       =  kwargs['candidate_labels']
      if "hypothesis_template" in kwargs:
        a		:      Any       =  kwargs['hypothesis_template']

      return preprocess_params, {}, {}







    def     lowercase_ (   self				:						int		,    __snake_case				:						Optional[Any]		,    __snake_case				:						List[Any]=None		,    __snake_case				:						List[str]="This is a sound of {}."			):
      if isinstance(__snake_case		,    __snake_case			):
        if audio.startswith('http://'			) or audio.startswith('https://'			):
          # We need to actually check for a real protocol, otherwise it's impossible to use a local file
          # like http_huggingface_co.png
          a		:      List[Any]       =  requests.get(__snake_case			).content
        else:
          with open(__snake_case		,    'rb'			) as f:
            a		:      List[str]       =  f.read()

      if isinstance(__snake_case		,    __snake_case			):
        a		:      Optional[Any]       =  ffmpeg_read(__snake_case		,    self.feature_extractor.sampling_rate			)

      if not isinstance(__snake_case		,    np.ndarray			):
        raise ValueError('We expect a numpy ndarray as input'			)
      if len(audio.shape			) != 1:
        raise ValueError('We expect a single channel audio input for ZeroShotAudioClassificationPipeline'			)

      a		:      str       =  self.feature_extractor(
          [audio]		,    sampling_rate=self.feature_extractor.sampling_rate		,    return_tensors='pt'			)
      a		:      Tuple       =  candidate_labels
      a		:      Union[str, Any]       =  [hypothesis_template.format(__snake_case			) for x in candidate_labels]
      a		:      int       =  self.tokenizer(__snake_case		,    return_tensors=self.framework		,    padding=__snake_case			)
      a		:      Any       =  [text_inputs]
      return inputs







    def     lowercase_ (   self				:						Optional[Any]		,    __snake_case				:						str			):
      a		:      Any       =  model_inputs.pop('candidate_labels'			)
      a		:      List[Any]       =  model_inputs.pop('text_inputs'			)
      if isinstance(text_inputs[0]		,    __snake_case			):
        a		:      str       =  text_inputs[0]
      else:
        # Batching case.
        a		:      Dict       =  text_inputs[0][0]

      a		:      List[Any]       =  self.model(**__snake_case		,    **__snake_case			)

      a		:      Any       =  {
          'candidate_labels': candidate_labels,
          'logits': outputs.logits_per_audio,
      }
      return model_outputs







    def     lowercase_ (   self				:						Union[str, Any]		,    __snake_case				:						str			):
      a		:      Optional[int]       =  model_outputs.pop('candidate_labels'			)
      a		:      List[str]       =  model_outputs['logits'][0]

      if self.framework == "pt":
        a		:      str       =  logits.softmax(dim=0			)
        a		:      List[Any]       =  probs.tolist()
      else:
        raise ValueError('`tf` framework not supported.'			)

      a		:      Dict       =  [
          {'score': score, 'label': candidate_label}
          for score, candidate_label in sorted(zip(__snake_case		,    __snake_case			)		,    key=lambda __snake_case			: -x[0]			)
      ]
      return result