


'''simple docstring'''

from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


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


lowerCamelCase							:   List[str]  						=	{
    'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json',
    'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json',
    'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json',
    'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json',
    'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json',
    'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json',
    'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json',
    'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json',
    'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json',
    'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json',
    'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json',
    'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json',
}
class   __lowerCAmelCase						(lowercase_     ):





      '''simple docstring'''






      lowerCAmelCase__					:     Any  					=							"""codegen"""
      lowerCAmelCase__					:     Union[str, Any]  					=							{
          """max_position_embeddings""": """n_positions""",
          """hidden_size""": """n_embd""",
          """num_attention_heads""": """n_head""",
          """num_hidden_layers""": """n_layer""",
      }



      def __init__(self    :    Any   ,						UpperCamelCase    :    List[Any]=50400   ,						UpperCamelCase    :    Optional[Any]=2048   ,						UpperCamelCase    :    List[Any]=2048   ,						UpperCamelCase    :    Optional[int]=4096   ,						UpperCamelCase    :    Union[str, Any]=28   ,						UpperCamelCase    :    Optional[Any]=16   ,						UpperCamelCase    :    Dict=64   ,						UpperCamelCase    :    Tuple=None   ,						UpperCamelCase    :    Optional[int]="gelu_new"   ,						UpperCamelCase    :    str=0.0   ,						UpperCamelCase    :    Dict=0.0   ,						UpperCamelCase    :    Tuple=0.0   ,						UpperCamelCase    :    int=1E-5   ,						UpperCamelCase    :    str=0.02   ,						UpperCamelCase    :    Union[str, Any]=True   ,						UpperCamelCase    :    Optional[Any]=50256   ,						UpperCamelCase    :    Dict=50256   ,						UpperCamelCase    :    int=False   ,						**UpperCamelCase    :    Optional[int]   ,						):

             '''simple docstring'''







             lowercase__      			= vocab_size
             lowercase__      			= n_ctx
             lowercase__      			= n_positions
             lowercase__      			= n_embd
             lowercase__      			= n_layer
             lowercase__      			= n_head
             lowercase__      			= n_inner
             lowercase__      			= rotary_dim
             lowercase__      			= activation_function
             lowercase__      			= resid_pdrop
             lowercase__      			= embd_pdrop
             lowercase__      			= attn_pdrop
             lowercase__      			= layer_norm_epsilon
             lowercase__      			= initializer_range
             lowercase__      			= use_cache

             lowercase__      			= bos_token_id
             lowercase__      			= eos_token_id

             super().__init__(
                 bos_token_id=UpperCamelCase   ,						eos_token_id=UpperCamelCase   ,						tie_word_embeddings=UpperCamelCase   ,						**UpperCamelCase )






class   __lowerCAmelCase						(lowercase_     ):





      '''simple docstring'''






      def __init__(self    :    Union[str, Any]   ,						UpperCamelCase    :    PretrainedConfig   ,						UpperCamelCase    :    str = "default"   ,						UpperCamelCase    :    List[PatchingSpec] = None   ,						UpperCamelCase    :    bool = False   ,						):

             '''simple docstring'''







             super().__init__(UpperCamelCase   ,						task=UpperCamelCase   ,						patching_specs=UpperCamelCase   ,						use_past=UpperCamelCase )
             if not getattr(self._config   ,						'''pad_token_id'''   ,						UpperCamelCase ):
                    # TODO: how to do that better?
                    lowercase__      			= 0



      @property
      def       UpperCamelCase__		(self    :    List[str] ):

             '''simple docstring'''







             lowercase__      			= OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} )
             if self.use_past:
                    self.fill_with_past_key_values_(UpperCamelCase   ,						direction='''inputs''' )
                    lowercase__      			= {0: '''batch''', 1: '''past_sequence + sequence'''}
             else:
                    lowercase__      			= {0: '''batch''', 1: '''sequence'''}

             return common_inputs



      @property
      def       UpperCamelCase__		(self    :    Any ):

             '''simple docstring'''







             return self._config.n_layer



      @property
      def       UpperCamelCase__		(self    :    List[Any] ):

             '''simple docstring'''







             return self._config.n_head



      def       UpperCamelCase__		(self    :    List[Any]   ,						UpperCamelCase    :    PreTrainedTokenizer   ,						UpperCamelCase    :    int = -1   ,						UpperCamelCase    :    int = -1   ,						UpperCamelCase    :    bool = False   ,						UpperCamelCase    :    Optional[TensorType] = None   ,						):

             '''simple docstring'''







             lowercase__      			= super(UpperCamelCase   ,						self ).generate_dummy_inputs(
                 UpperCamelCase   ,						batch_size=UpperCamelCase   ,						seq_length=UpperCamelCase   ,						is_pair=UpperCamelCase   ,						framework=UpperCamelCase )

             # We need to order the input in the way they appears in the forward()
             lowercase__      			= OrderedDict({'''input_ids''': common_inputs['''input_ids''']} )

             # Need to add the past_keys
             if self.use_past:
                    if not is_torch_available():
                           raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' )
                    else:
                           import torch

                           lowercase__			,lowercase__      			= common_inputs['''input_ids'''].shape
                           # Not using the same length for past_key_values
                           lowercase__      			= seqlen + 2
                           lowercase__      			= (
                               batch,
                               self.num_attention_heads,
                               past_key_values_length,
                               self._config.hidden_size // self.num_attention_heads,
                           )
                           lowercase__      			= [
                               (torch.zeros(UpperCamelCase ), torch.zeros(UpperCamelCase )) for _ in range(self.num_layers )
                           ]

             lowercase__      			= common_inputs['''attention_mask''']
             if self.use_past:
                    lowercase__      			= ordered_inputs['''attention_mask'''].dtype
                    lowercase__      			= torch.cat(
                        [ordered_inputs['''attention_mask'''], torch.ones(UpperCamelCase   ,						UpperCamelCase   ,						dtype=UpperCamelCase )]   ,						dim=1 )

             return ordered_inputs






      @property
      def       UpperCamelCase__		(self    :    Optional[Any] ):

             '''simple docstring'''







             return 13









'''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							:Union[str, Any]				    =					logging.get_logger(__name__)







@add_end_docstrings(__UpperCAmelCase )
class 	_lowerCAmelCase							(			__UpperCAmelCase ):


	def __init__(self       ,      **lowercase							):
				super().__init__(**lowercase							)

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


	def __call__(self       ,      lowercase       ,      **lowercase							):
				return super().__call__(lowercase       ,      **lowercase							)


	def     _a	(self       ,      **lowercase							):
				A_	:						Tuple	=     {}
				if "candidate_labels" in kwargs:
							A_	:						Dict	=     kwargs["""candidate_labels"""]
				if "hypothesis_template" in kwargs:
							A_	:						Optional[Any]	=     kwargs["""hypothesis_template"""]

				return preprocess_params, {}, {}


	def     _a	(self       ,      lowercase       ,      lowercase=None       ,      lowercase="This is a sound of {}."							):
				if isinstance(lowercase       ,      lowercase							):
							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_	:						Dict	=     requests.get(lowercase							).content
							else:
										with open(lowercase       ,      """rb"""							) as f:
													A_	:						List[str]	=     f.read()

				if isinstance(lowercase       ,      lowercase							):
							A_	:						List[Any]	=     ffmpeg_read(lowercase       ,      self.feature_extractor.sampling_rate							)

				if not isinstance(lowercase       ,      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_	:						int	=     self.feature_extractor(
				    [audio]       ,      sampling_rate=self.feature_extractor.sampling_rate       ,      return_tensors="""pt"""							)
				A_	:						List[Any]	=     candidate_labels
				A_	:						str	=     [hypothesis_template.format(lowercase							) for x in candidate_labels]
				A_	:						Optional[Any]	=     self.tokenizer(lowercase       ,      return_tensors=self.framework       ,      padding=lowercase							)
				A_	:						Optional[Any]	=     [text_inputs]
				return inputs


	def     _a	(self       ,      lowercase							):
				A_	:						Union[str, Any]	=     model_inputs.pop("""candidate_labels"""							)
				A_	:						List[Any]	=     model_inputs.pop("""text_inputs"""							)
				if isinstance(text_inputs[0]       ,      lowercase							):
							A_	:						Union[str, Any]	=     text_inputs[0]
				else:
							# Batching case.
							A_	:						Optional[int]	=     text_inputs[0][0]

				A_	:						str	=     self.model(**lowercase       ,      **lowercase							)

				A_	:						Union[str, Any]	=     {
				    """candidate_labels""": candidate_labels,
				    """logits""": outputs.logits_per_audio,
				}
				return model_outputs


	def     _a	(self       ,      lowercase							):
				A_	:						Union[str, Any]	=     model_outputs.pop("""candidate_labels"""							)
				A_	:						List[Any]	=     model_outputs["""logits"""][0]

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

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