





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

@add_end_docstrings(a_			)
class 	A_       (a_			):
	def __init__(    self							,					**_A		):






				'''simple docstring'''







				super().__init__(**_A		)

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






				'''simple docstring'''







				return super().__call__(_A							,					**_A		)
	def      _lowercase				(    self							,					**_A		):






				'''simple docstring'''







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

				return preprocess_params, {}, {}
	def      _lowercase				(    self							,					_A							,					_A=None							,					_A="This is a sound of {}."		):






				'''simple docstring'''







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

				if isinstance(_A							,					_A		):
							UpperCAmelCase   		=				ffmpeg_read(_A							,					self.feature_extractor.sampling_rate		)

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

				UpperCAmelCase   		=				self.feature_extractor(
				    [audio]							,					sampling_rate=self.feature_extractor.sampling_rate							,					return_tensors='''pt'''		)
				UpperCAmelCase   		=				candidate_labels
				UpperCAmelCase   		=				[hypothesis_template.format(_A		) for x in candidate_labels]
				UpperCAmelCase   		=				self.tokenizer(_A							,					return_tensors=self.framework							,					padding=_A		)
				UpperCAmelCase   		=				[text_inputs]
				return inputs
	def      _lowercase				(    self							,					_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				model_inputs.pop('''candidate_labels'''		)
				UpperCAmelCase   		=				model_inputs.pop('''text_inputs'''		)
				if isinstance(text_inputs[0]							,					_A		):
							UpperCAmelCase   		=				text_inputs[0]
				else:
							# Batching case.
							UpperCAmelCase   		=				text_inputs[0][0]

				UpperCAmelCase   		=				self.model(**_A							,					**_A		)

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







	def      _lowercase				(    self							,					_A		):






				'''simple docstring'''







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

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

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





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowercase  :					str						    =							{
    """configuration_funnel""": ["""FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FunnelConfig"""],
    """convert_funnel_original_tf_checkpoint_to_pytorch""": [],
    """tokenization_funnel""": ["""FunnelTokenizer"""],
}

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

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase  :					List[str]						    =							[
      """FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """FunnelBaseModel""",
      """FunnelForMaskedLM""",
      """FunnelForMultipleChoice""",
      """FunnelForPreTraining""",
      """FunnelForQuestionAnswering""",
      """FunnelForSequenceClassification""",
      """FunnelForTokenClassification""",
      """FunnelModel""",
      """FunnelPreTrainedModel""",
      """load_tf_weights_in_funnel""",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase  :					Optional[Any]						    =							[
      """TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """TFFunnelBaseModel""",
      """TFFunnelForMaskedLM""",
      """TFFunnelForMultipleChoice""",
      """TFFunnelForPreTraining""",
      """TFFunnelForQuestionAnswering""",
      """TFFunnelForSequenceClassification""",
      """TFFunnelForTokenClassification""",
      """TFFunnelModel""",
      """TFFunnelPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig
  from .tokenization_funnel import FunnelTokenizer

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_funnel_fast import FunnelTokenizerFast

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_funnel import (
        FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
        FunnelBaseModel,
        FunnelForMaskedLM,
        FunnelForMultipleChoice,
        FunnelForPreTraining,
        FunnelForQuestionAnswering,
        FunnelForSequenceClassification,
        FunnelForTokenClassification,
        FunnelModel,
        FunnelPreTrainedModel,
        load_tf_weights_in_funnel,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_funnel import (
        TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFFunnelBaseModel,
        TFFunnelForMaskedLM,
        TFFunnelForMultipleChoice,
        TFFunnelForPreTraining,
        TFFunnelForQuestionAnswering,
        TFFunnelForSequenceClassification,
        TFFunnelForTokenClassification,
        TFFunnelModel,
        TFFunnelPreTrainedModel,
    )

else:
  import sys

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