






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


_SCREAMING_SNAKE_CASE   :							Any          =		logging.get_logger(__name__)






@add_end_docstrings(__snake_case						)
class 	a		(   __snake_case						):






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






    def   UpperCamelCase			(			self	:				List[str]			,		**__SCREAMING_SNAKE_CASE	:				Optional[Any]   )	->						Optional[int]:
      lowerCamelCase_       	=		{}
      if "candidate_labels" in kwargs:
        lowerCamelCase_       	=		kwargs['candidate_labels']
      if "hypothesis_template" in kwargs:
        lowerCamelCase_       	=		kwargs['hypothesis_template']

      return preprocess_params, {}, {}






    def   UpperCamelCase			(			self	:				Optional[int]			,		__SCREAMING_SNAKE_CASE	:				Any			,		__SCREAMING_SNAKE_CASE	:				Dict=None			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]="This is a sound of {}."   )	->						Dict:
      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_       	=		requests.get(__SCREAMING_SNAKE_CASE   ).content
        else:
          with open(__SCREAMING_SNAKE_CASE			,		'rb'   ) as f:
            lowerCamelCase_       	=		f.read()

      if isinstance(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   ):
        lowerCamelCase_       	=		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_       	=		self.feature_extractor(
          [audio]			,		sampling_rate=self.feature_extractor.sampling_rate			,		return_tensors='pt'   )
      lowerCamelCase_       	=		candidate_labels
      lowerCamelCase_       	=		[hypothesis_template.format(__SCREAMING_SNAKE_CASE   ) for x in candidate_labels]
      lowerCamelCase_       	=		self.tokenizer(__SCREAMING_SNAKE_CASE			,		return_tensors=self.framework			,		padding=__SCREAMING_SNAKE_CASE   )
      lowerCamelCase_       	=		[text_inputs]
      return inputs






    def   UpperCamelCase			(			self	:				int			,		__SCREAMING_SNAKE_CASE	:				Tuple   )	->						Optional[int]:
      lowerCamelCase_       	=		model_inputs.pop('candidate_labels'   )
      lowerCamelCase_       	=		model_inputs.pop('text_inputs'   )
      if isinstance(text_inputs[0]			,		__SCREAMING_SNAKE_CASE   ):
        lowerCamelCase_       	=		text_inputs[0]
      else:
        # Batching case.
        lowerCamelCase_       	=		text_inputs[0][0]

      lowerCamelCase_       	=		self.model(**__SCREAMING_SNAKE_CASE			,		**__SCREAMING_SNAKE_CASE   )

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






    def   UpperCamelCase			(			self	:				str			,		__SCREAMING_SNAKE_CASE	:				Tuple   )	->						int:
      lowerCamelCase_       	=		model_outputs.pop('candidate_labels'   )
      lowerCamelCase_       	=		model_outputs['logits'][0]

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

      lowerCamelCase_       	=		[
          {'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 ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


_SCREAMING_SNAKE_CASE   :							List[Any]          =		{'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']}

try:
  if not is_sentencepiece_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _SCREAMING_SNAKE_CASE   :							Union[str, Any]          =		['''PLBartTokenizer''']

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _SCREAMING_SNAKE_CASE   :							List[str]          =		[
      '''PLBART_PRETRAINED_MODEL_ARCHIVE_LIST''',
      '''PLBartForCausalLM''',
      '''PLBartForConditionalGeneration''',
      '''PLBartForSequenceClassification''',
      '''PLBartModel''',
      '''PLBartPreTrainedModel''',
  ]


if TYPE_CHECKING:
  from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig

  try:
    if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_plbart import PLBartTokenizer

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_plbart import (
        PLBART_PRETRAINED_MODEL_ARCHIVE_LIST,
        PLBartForCausalLM,
        PLBartForConditionalGeneration,
        PLBartForSequenceClassification,
        PLBartModel,
        PLBartPreTrainedModel,
    )


else:
  import sys

  _SCREAMING_SNAKE_CASE   :							Optional[Any]          =		_LazyModule(__name__, globals()['''__file__'''], _import_structure)




