






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(lowercase_)
class 			snake_case__   (							lowercase_):

       '''simple docstring'''



       def __init__(							self			,						**a__    ) ->      str:






            '''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__    ) ->      Tuple:






            '''simple docstring'''





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



       def 					__lowercase						(							self			,						**a__    ) ->      str:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						{}
            if "candidate_labels" in kwargs:
                 __snake_case			:List[str]          =						kwargs["""candidate_labels"""]
            if "hypothesis_template" in kwargs:
                 __snake_case			:Union[str, Any]          =						kwargs["""hypothesis_template"""]

            return preprocess_params, {}, {}



       def 					__lowercase						(							self			,						a__			,						a__=None			,						a__="This is a sound of {}."    ) ->      int:






            '''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
                      __snake_case			:List[str]          =						requests.get(a__    ).content
                 else:
                      with open(a__			,						"""rb"""    ) as f:
                           __snake_case			:Dict          =						f.read()

            if isinstance(a__			,						a__    ):
                 __snake_case			:Tuple          =						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"""    )

            __snake_case			:str          =						self.feature_extractor(
                [audio]			,						sampling_rate=self.feature_extractor.sampling_rate			,						return_tensors="""pt"""    )
            __snake_case			:int          =						candidate_labels
            __snake_case			:Optional[int]          =						[hypothesis_template.format(a__    ) for x in candidate_labels]
            __snake_case			:Optional[Any]          =						self.tokenizer(a__			,						return_tensors=self.framework			,						padding=a__    )
            __snake_case			:int          =						[text_inputs]
            return inputs



       def 					__lowercase						(							self			,						a__    ) ->      str:






            '''simple docstring'''





            __snake_case			:Tuple          =						model_inputs.pop("""candidate_labels"""    )
            __snake_case			:List[Any]          =						model_inputs.pop("""text_inputs"""    )
            if isinstance(text_inputs[0]			,						a__    ):
                 __snake_case			:List[Any]          =						text_inputs[0]
            else:
                 # Batching case.
                 __snake_case			:Optional[int]          =						text_inputs[0][0]

            __snake_case			:Union[str, Any]          =						self.model(**a__			,						**a__    )

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



       def 					__lowercase						(							self			,						a__    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						model_outputs.pop("""candidate_labels"""    )
            __snake_case			:int          =						model_outputs["""logits"""][0]

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

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










import unittest

from transformers import load_tool

from .test_tools_common import ToolTesterMixin


lowerCamelCase__							=     """
Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.

In March 2021, Hugging Face raised $40 million in a Series B funding round.[3]

On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]
"""




class 			snake_case__   (							unittest.TestCase	,    lowercase_):

       '''simple docstring'''



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:int          =						load_tool("""text-question-answering"""    )
            self.tool.setup()
            __snake_case			:Tuple          =						load_tool("""text-question-answering"""			,						remote=a__    )



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.tool(a__			,						"""What did Hugging Face do in April 2021?"""    )
            self.assertEqual(a__			,						"""launched the BigScience Research Workshop"""    )



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.remote_tool(a__			,						"""What did Hugging Face do in April 2021?"""    )
            self.assertEqual(a__			,						"""launched the BigScience Research Workshop"""    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						self.tool(text=a__			,						question="""What did Hugging Face do in April 2021?"""    )
            self.assertEqual(a__			,						"""launched the BigScience Research Workshop"""    )



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.remote_tool(text=a__			,						question="""What did Hugging Face do in April 2021?"""    )
            self.assertEqual(a__			,						"""launched the BigScience Research Workshop"""    )


