


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







@add_end_docstrings(UpperCAmelCase__      )
class A__       (						UpperCAmelCase__      ):






      def __init__( self			:Dict     ,						**SCREAMING_SNAKE_CASE			:List[Any]	)       ->					Dict:




             '''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			:Any     ,						SCREAMING_SNAKE_CASE			:Union[np.ndarray, bytes, str]     ,						**SCREAMING_SNAKE_CASE			:Union[str, Any]	)       ->					Optional[int]:




             '''simple docstring'''
             return super().__call__(SCREAMING_SNAKE_CASE     ,						**SCREAMING_SNAKE_CASE	)






      def __UpperCAmelCase       ( self			:Tuple     ,						**SCREAMING_SNAKE_CASE			:Optional[int]	)       ->					List[str]:




             '''simple docstring'''
             _a    : str     					={}
             if "candidate_labels" in kwargs:
                    _a    : Tuple     					=kwargs["""candidate_labels"""]
             if "hypothesis_template" in kwargs:
                    _a    : Optional[int]     					=kwargs["""hypothesis_template"""]

             return preprocess_params, {}, {}






      def __UpperCAmelCase       ( self			:Tuple     ,						SCREAMING_SNAKE_CASE			:Tuple     ,						SCREAMING_SNAKE_CASE			:List[Any]=None     ,						SCREAMING_SNAKE_CASE			:Any="This is a sound of {}."	)       ->					Tuple:




             '''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    : Tuple     					=requests.get(SCREAMING_SNAKE_CASE	).content
                    else:
                           with open(SCREAMING_SNAKE_CASE     ,						"""rb"""	) as f:
                                  _a    : Dict     					=f.read()

             if isinstance(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	):
                    _a    : List[Any]     					=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    : Optional[Any]     					=self.feature_extractor(
                 [audio]     ,						sampling_rate=self.feature_extractor.sampling_rate     ,						return_tensors="""pt"""	)
             _a    : str     					=candidate_labels
             _a    : Optional[int]     					=[hypothesis_template.format(SCREAMING_SNAKE_CASE	) for x in candidate_labels]
             _a    : int     					=self.tokenizer(SCREAMING_SNAKE_CASE     ,						return_tensors=self.framework     ,						padding=SCREAMING_SNAKE_CASE	)
             _a    : Union[str, Any]     					=[text_inputs]
             return inputs






      def __UpperCAmelCase       ( self			:int     ,						SCREAMING_SNAKE_CASE			:Any	)       ->					List[Any]:




             '''simple docstring'''
             _a    : Tuple     					=model_inputs.pop("""candidate_labels"""	)
             _a    : Tuple     					=model_inputs.pop("""text_inputs"""	)
             if isinstance(text_inputs[0]     ,						SCREAMING_SNAKE_CASE	):
                    _a    : List[Any]     					=text_inputs[0]
             else:
                    # Batching case.
                    _a    : Tuple     					=text_inputs[0][0]

             _a    : str     					=self.model(**SCREAMING_SNAKE_CASE     ,						**SCREAMING_SNAKE_CASE	)

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






      def __UpperCAmelCase       ( self			:Any     ,						SCREAMING_SNAKE_CASE			:int	)       ->					Any:




             '''simple docstring'''
             _a    : Tuple     					=model_outputs.pop("""candidate_labels"""	)
             _a    : int     					=model_outputs["""logits"""][0]

             if self.framework == "pt":
                    _a    : Optional[int]     					=logits.softmax(dim=0	)
                    _a    : Tuple     					=probs.tolist()
             else:
                    raise ValueError("""`tf` framework not supported."""	)

             _a    : Any     					=[
                 {"""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'''







A__:    Tuple					    =       '''
# Installazione di Transformers
! pip install transformers datasets
# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e
# rimuovi la modalità commento al comando seguente.
# ! pip install git+https://github.com/huggingface/transformers.git
'''

A__:    Tuple					    =       [{'''type''': '''code''', '''content''': INSTALL_CONTENT}]
A__:    Any					    =       {
    '''{processor_class}''': '''FakeProcessorClass''',
    '''{model_class}''': '''FakeModelClass''',
    '''{object_class}''': '''FakeObjectClass''',
}


