



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


__snake_case						:List[Any]      		=     logging.get_logger(__name__)

@add_end_docstrings(__UpperCAmelCase    )
class     _A       (	__UpperCAmelCase    ):



       def __init__(		self							:     Any     ,		**__SCREAMING_SNAKE_CASE							:     Union[str, Any]):


           '''simple docstring'''

           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							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     Union[np.ndarray, bytes, str]     ,		**__SCREAMING_SNAKE_CASE							:     int):


           '''simple docstring'''

           return super().__call__(__SCREAMING_SNAKE_CASE     ,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase			(		self							:     Tuple     ,		**__SCREAMING_SNAKE_CASE							:     Any):


           '''simple docstring'''

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

           return preprocess_params, {}, {}



       def 		_lowerCamelCase			(		self							:     List[Any]     ,		__SCREAMING_SNAKE_CASE							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     List[str]=None     ,		__SCREAMING_SNAKE_CASE							:     Tuple="This is a sound of {}."):


           '''simple docstring'''

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

           if isinstance(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE):
               __a						       =				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''')

           __a						       =				self.feature_extractor(
               [audio]     ,		sampling_rate=self.feature_extractor.sampling_rate     ,		return_tensors='''pt''')
           __a						       =				candidate_labels
           __a						       =				[hypothesis_template.format(__SCREAMING_SNAKE_CASE) for x in candidate_labels]
           __a						       =				self.tokenizer(__SCREAMING_SNAKE_CASE     ,		return_tensors=self.framework     ,		padding=__SCREAMING_SNAKE_CASE)
           __a						       =				[text_inputs]
           return inputs



       def 		_lowerCamelCase			(		self							:     List[Any]     ,		__SCREAMING_SNAKE_CASE							:     Optional[int]):


           '''simple docstring'''

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

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

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





       def 		_lowerCamelCase			(		self							:     Optional[int]     ,		__SCREAMING_SNAKE_CASE							:     Optional[int]):


           '''simple docstring'''

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

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

           __a						       =				[
               {'''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"""







import warnings

from ...utils import logging
from .image_processing_beit import BeitImageProcessor


__SCREAMING_SNAKE_CASE    	=logging.get_logger(__name__)







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,*__UpperCamelCase     ,**__UpperCamelCase			)	->      None:


        '''simple docstring'''


        warnings.warn(
            'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
            ' use BeitImageProcessor instead.'     ,__UpperCamelCase     ,)
        super().__init__(*__UpperCamelCase     ,**__UpperCamelCase			)

