






'''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


a_					= logging.get_logger(__name__)






@add_end_docstrings(lowercase_				)
class      __SCREAMING_SNAKE_CASE      (			lowercase_				):




	def __init__(      self	:							int					,      **__lowercase	:							Any      )	->						Dict:
							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]					,      __lowercase	:							Union[np.ndarray, bytes, str]					,      **__lowercase	:							Any      )	->						Optional[Any]:
							return super().__call__(UpperCamelCase__					,      **UpperCamelCase__      )




	def      __magic_name__	(      self	:							int					,      **__lowercase	:							List[Any]      )	->						Tuple:
							SCREAMING_SNAKE_CASE__     :				Dict									={}
							if "candidate_labels" in kwargs:
													SCREAMING_SNAKE_CASE__     :				List[Any]									=kwargs['''candidate_labels''']
							if "hypothesis_template" in kwargs:
													SCREAMING_SNAKE_CASE__     :				Tuple									=kwargs['''hypothesis_template''']

							return preprocess_params, {}, {}




	def      __magic_name__	(      self	:							Dict					,      __lowercase	:							Any					,      __lowercase	:							Dict=None					,      __lowercase	:							List[str]="This is a sound of {}."      )	->						Optional[int]:







							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
																			SCREAMING_SNAKE_CASE__     :				List[Any]									=requests.get(UpperCamelCase__      ).content
													else:
																			with open(UpperCamelCase__					,      '''rb'''      ) as f:
																									SCREAMING_SNAKE_CASE__     :				Tuple									=f.read()

							if isinstance(UpperCamelCase__					,      UpperCamelCase__      ):
													SCREAMING_SNAKE_CASE__     :				Dict									=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'''      )

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




	def      __magic_name__	(      self	:							int					,      __lowercase	:							Optional[int]      )	->						str:
							SCREAMING_SNAKE_CASE__     :				int									=model_inputs.pop('''candidate_labels'''      )
							SCREAMING_SNAKE_CASE__     :				str									=model_inputs.pop('''text_inputs'''      )
							if isinstance(text_inputs[0]					,      UpperCamelCase__      ):
													SCREAMING_SNAKE_CASE__     :				Optional[int]									=text_inputs[0]
							else:
													# Batching case.
													SCREAMING_SNAKE_CASE__     :				Dict									=text_inputs[0][0]

							SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=self.model(**UpperCamelCase__					,      **UpperCamelCase__      )

							SCREAMING_SNAKE_CASE__     :				int									={
							    '''candidate_labels''': candidate_labels,
							    '''logits''': outputs.logits_per_audio,
							}
							return model_outputs




	def      __magic_name__	(      self	:							Dict					,      __lowercase	:							List[str]      )	->						List[str]:
							SCREAMING_SNAKE_CASE__     :				Optional[int]									=model_outputs.pop('''candidate_labels'''      )
							SCREAMING_SNAKE_CASE__     :				Any									=model_outputs['''logits'''][0]

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

							SCREAMING_SNAKE_CASE__     :				List[Any]									=[
							    {'''score''': score, '''label''': candidate_label}
							    for score, candidate_label in sorted(zip(UpperCamelCase__					,      UpperCamelCase__      )					,      key=lambda __lowercase      : -x[0]      )
							]
							return result







'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging


a_					= logging.get_logger(__name__)

a_					= {
    'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json',
    # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox
}






class      __SCREAMING_SNAKE_CASE      (			lowerCamelCase				):
 snake_case_  							=							"""gpt_neox"""




 def __init__(      self	:							List[Any]					,      __lowercase	:							Union[str, Any]=5_04_32					,      __lowercase	:							int=61_44					,      __lowercase	:							Tuple=44					,      __lowercase	:							List[str]=64					,      __lowercase	:							str=2_45_76					,      __lowercase	:							Dict="gelu"					,      __lowercase	:							Tuple=0.25					,      __lowercase	:							Tuple=1_00_00					,      __lowercase	:							Tuple=0.0					,      __lowercase	:							str=0.0					,      __lowercase	:							List[Any]=0.1					,      __lowercase	:							Dict=20_48					,      __lowercase	:							Any=0.02					,      __lowercase	:							Dict=1e-5					,      __lowercase	:							List[Any]=True					,      __lowercase	:							str=0					,      __lowercase	:							Optional[Any]=2					,      __lowercase	:							Tuple=False					,      __lowercase	:							List[Any]=True					,      __lowercase	:							Optional[Any]=None					,      **__lowercase	:							Any					,      )	->						Dict:
       super().__init__(bos_token_id=__lowercase					,      eos_token_id=__lowercase					,      **__lowercase      )
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=vocab_size
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=max_position_embeddings
       SCREAMING_SNAKE_CASE__     :				Any									=hidden_size
       SCREAMING_SNAKE_CASE__     :				str									=num_hidden_layers
       SCREAMING_SNAKE_CASE__     :				Any									=num_attention_heads
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=intermediate_size
       SCREAMING_SNAKE_CASE__     :				Dict									=hidden_act
       SCREAMING_SNAKE_CASE__     :				str									=rotary_pct
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=rotary_emb_base
       SCREAMING_SNAKE_CASE__     :				List[Any]									=attention_dropout
       SCREAMING_SNAKE_CASE__     :				List[Any]									=hidden_dropout
       SCREAMING_SNAKE_CASE__     :				str									=classifier_dropout
       SCREAMING_SNAKE_CASE__     :				Any									=initializer_range
       SCREAMING_SNAKE_CASE__     :				Dict									=layer_norm_eps
       SCREAMING_SNAKE_CASE__     :				Any									=use_cache
       SCREAMING_SNAKE_CASE__     :				Tuple									=tie_word_embeddings
       SCREAMING_SNAKE_CASE__     :				Tuple									=use_parallel_residual
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=rope_scaling
       self._rope_scaling_validation()

       if self.hidden_size % self.num_attention_heads != 0:
             raise ValueError(
                 '''The hidden size is not divisble by the number of attention heads! Make sure to update them!'''      )




 def      __magic_name__	(      self	:							Optional[Any]      )	->						Optional[Any]:
       if self.rope_scaling is None:
             return

       if not isinstance(self.rope_scaling					,      __lowercase      ) or len(self.rope_scaling      ) != 2:
             raise ValueError(
                 '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
                 F"got {self.rope_scaling}"      )
       SCREAMING_SNAKE_CASE__     :				int									=self.rope_scaling.get('''type'''					,      __lowercase      )
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=self.rope_scaling.get('''factor'''					,      __lowercase      )
       if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
             raise ValueError(
                 F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"      )
       if rope_scaling_factor is None or not isinstance(__lowercase					,      __lowercase      ) or rope_scaling_factor <= 1.0:
             raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}"      )