
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[int]       			=  logging.get_logger(__name__)




@add_end_docstrings(_A	)
class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  def __init__(					self     :					List[str]     ,				**UpperCamelCase__     :					Dict       )     ->      List[Any]:







    """simple docstring"""






    super().__init__(**UpperCamelCase__       )

    if self.framework != "pt":
      raise ValueError(F'''The {self.__class__} is only available in PyTorch.'''       )
    # No specific FOR_XXX available yet
  def __call__(					self     :					Optional[int]     ,				UpperCamelCase__     :					Union[np.ndarray, bytes, str]     ,				**UpperCamelCase__     :					List[str]       )     ->      Union[str, Any]:







    """simple docstring"""






    return super().__call__(UpperCamelCase__     ,				**UpperCamelCase__       )
  def 				_lowercase				(					self     :					Dict     ,				**UpperCamelCase__     :					Dict       )     ->      Tuple:







    """simple docstring"""






    __magic_name__								=			{}
    if "candidate_labels" in kwargs:
      __magic_name__								=			kwargs["""candidate_labels"""]
    if "hypothesis_template" in kwargs:
      __magic_name__								=			kwargs["""hypothesis_template"""]

    return preprocess_params, {}, {}
  def 				_lowercase				(					self     :					str     ,				UpperCamelCase__     :					Dict     ,				UpperCamelCase__     :					Optional[int]=None     ,				UpperCamelCase__     :					Any="This is a sound of {}."       )     ->      int:







    """simple docstring"""






    if isinstance(UpperCamelCase__     ,				UpperCamelCase__       ):
      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
        __magic_name__								=			requests.get(UpperCamelCase__       ).content
      else:
        with open(UpperCamelCase__     ,				"""rb"""       ) as f:
          __magic_name__								=			f.read()

    if isinstance(UpperCamelCase__     ,				UpperCamelCase__       ):
      __magic_name__								=			ffmpeg_read(UpperCamelCase__     ,				self.feature_extractor.sampling_rate       )

    if not isinstance(UpperCamelCase__     ,				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"""       )

    __magic_name__								=			self.feature_extractor(
        [audio]     ,				sampling_rate=self.feature_extractor.sampling_rate     ,				return_tensors="""pt"""       )
    __magic_name__								=			candidate_labels
    __magic_name__								=			[hypothesis_template.format(UpperCamelCase__       ) for x in candidate_labels]
    __magic_name__								=			self.tokenizer(UpperCamelCase__     ,				return_tensors=self.framework     ,				padding=UpperCamelCase__       )
    __magic_name__								=			[text_inputs]
    return inputs
  def 				_lowercase				(					self     :					Optional[int]     ,				UpperCamelCase__     :					Union[str, Any]       )     ->      Any:







    """simple docstring"""






    __magic_name__								=			model_inputs.pop("""candidate_labels"""       )
    __magic_name__								=			model_inputs.pop("""text_inputs"""       )
    if isinstance(text_inputs[0]     ,				UpperCamelCase__       ):
      __magic_name__								=			text_inputs[0]
    else:
      # Batching case.
      __magic_name__								=			text_inputs[0][0]

    __magic_name__								=			self.model(**UpperCamelCase__     ,				**UpperCamelCase__       )

    __magic_name__								=			{
        """candidate_labels""": candidate_labels,
        """logits""": outputs.logits_per_audio,
    }
    return model_outputs





  def 				_lowercase				(					self     :					int     ,				UpperCamelCase__     :					int       )     ->      Dict:







    """simple docstring"""






    __magic_name__								=			model_outputs.pop("""candidate_labels"""       )
    __magic_name__								=			model_outputs["""logits"""][0]

    if self.framework == "pt":
      __magic_name__								=			logits.softmax(dim=0       )
      __magic_name__								=			probs.tolist()
    else:
      raise ValueError("""`tf` framework not supported."""       )

    __magic_name__								=			[
        {"""score""": score, """label""": candidate_label}
        for score, candidate_label in sorted(zip(UpperCamelCase__     ,				UpperCamelCase__       )     ,				key=lambda UpperCamelCase__       : -x[0]       )
    ]
    return result



import argparse

import torch

from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

def a__       (			A_,	A_,	A_   ):






  '''simple docstring'''





  if gpta_config_file == "":
    __magic_name__								=			GPTaConfig()
  else:
    __magic_name__								=			GPTaConfig.from_json_file(A_   )
  __magic_name__								=			GPTaModel(A_   )

  # Load weights from numpy
  load_tf_weights_in_gpta(A_,	A_,	A_   )

  # Save pytorch-model
  __magic_name__								=			pytorch_dump_folder_path + """/""" + WEIGHTS_NAME
  __magic_name__								=			pytorch_dump_folder_path + """/""" + CONFIG_NAME
  print(f'''Save PyTorch model to {pytorch_weights_dump_path}'''   )
  torch.save(model.state_dict(),	A_   )
  print(f'''Save configuration file to {pytorch_config_dump_path}'''   )
  with open(A_,	"""w""",	encoding="""utf-8"""   ) as f:
    f.write(config.to_json_string()   )


if __name__ == "__main__":
    __lowerCAmelCase     :	List[str]       			=  argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
    )
    parser.add_argument(
        '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
    )
    parser.add_argument(
        '--gpt2_config_file',
        default='',
        type=str,
        help=(
            'An optional config json file corresponding to the pre-trained OpenAI model. \n'
            'This specifies the model architecture.'
        ),
    )
    __lowerCAmelCase     :	Tuple       			=  parser.parse_args()
    convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)

