
"""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__   					=		logging.get_logger(__name__)




@add_end_docstrings(_lowerCamelCase)
class  A__       (	_lowerCamelCase):

		def __init__(      self       ,		**_SCREAMING_SNAKE_CASE ):
			super().__init__(**_SCREAMING_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       ,		_SCREAMING_SNAKE_CASE       ,		**_SCREAMING_SNAKE_CASE ):
			return super().__call__(_SCREAMING_SNAKE_CASE       ,		**_SCREAMING_SNAKE_CASE )

		def 							__lowerCamelCase							(      self       ,		**_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						List[str]									=      {}
			if "candidate_labels" in kwargs:
				__lowerCAmelCase			:						str									=      kwargs['candidate_labels']
			if "hypothesis_template" in kwargs:
				__lowerCAmelCase			:						List[Any]									=      kwargs['hypothesis_template']

			return preprocess_params, {}, {}

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE=None       ,		_SCREAMING_SNAKE_CASE="This is a sound of {}." ):
			if isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_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
					__lowerCAmelCase			:						Union[str, Any]									=      requests.get(_SCREAMING_SNAKE_CASE ).content
				else:
					with open(_SCREAMING_SNAKE_CASE       ,		'rb' ) as f:
						__lowerCAmelCase			:						str									=      f.read()

			if isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				__lowerCAmelCase			:						Optional[int]									=      ffmpeg_read(_SCREAMING_SNAKE_CASE       ,		self.feature_extractor.sampling_rate )

			if not isinstance(_SCREAMING_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' )

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

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						str									=      model_inputs.pop('candidate_labels' )
			__lowerCAmelCase			:						str									=      model_inputs.pop('text_inputs' )
			if isinstance(text_inputs[0]       ,		_SCREAMING_SNAKE_CASE ):
				__lowerCAmelCase			:						str									=      text_inputs[0]
			else:
				# Batching case.
				__lowerCAmelCase			:						Union[str, Any]									=      text_inputs[0][0]

			__lowerCAmelCase			:						Optional[int]									=      self.model(**_SCREAMING_SNAKE_CASE       ,		**_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						Tuple									=      {
			    'candidate_labels': candidate_labels,
			    'logits': outputs.logits_per_audio,
			}
			return model_outputs







		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						Tuple									=      model_outputs.pop('candidate_labels' )
			__lowerCAmelCase			:						str									=      model_outputs['logits'][0]

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

			__lowerCAmelCase			:						List[str]									=      [
			    {'score': score, 'label': candidate_label}
			    for score, candidate_label in sorted(zip(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE )       ,		key=lambda _SCREAMING_SNAKE_CASE : -x[0] )
			]
			return result
'''simple docstring'''




from typing import TYPE_CHECKING

from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available
from ...utils import OptionalDependencyNotAvailable


__SCREAMING_SNAKE_CASE       :     Optional[int]     =  {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]}

try:
  if not is_tokenizers_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __SCREAMING_SNAKE_CASE       :     Tuple     =  ["""GPTNeoXTokenizerFast"""]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __SCREAMING_SNAKE_CASE       :     Dict     =  [
      """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """GPTNeoXForCausalLM""",
      """GPTNeoXForQuestionAnswering""",
      """GPTNeoXForSequenceClassification""",
      """GPTNeoXForTokenClassification""",
      """GPTNeoXLayer""",
      """GPTNeoXModel""",
      """GPTNeoXPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_gpt_neox import (
        GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST,
        GPTNeoXForCausalLM,
        GPTNeoXForQuestionAnswering,
        GPTNeoXForSequenceClassification,
        GPTNeoXForTokenClassification,
        GPTNeoXLayer,
        GPTNeoXModel,
        GPTNeoXPreTrainedModel,
    )


else:
  import sys

  __SCREAMING_SNAKE_CASE       :     Any     =  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

