





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


_UpperCAmelCase        =				logging.get_logger(__name__)



@add_end_docstrings(lowerCAmelCase_     )
class 							_UpperCamelCase					(	lowerCAmelCase_     ):

       def __init__(		self: int					,   **_SCREAMING_SNAKE_CASE: List[str]		)       -> 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: List[str]					,   _SCREAMING_SNAKE_CASE: Union[np.ndarray, bytes, str]					,   **_SCREAMING_SNAKE_CASE: List[str]		)       -> Optional[int]:




              """simple docstring"""


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

       def lowercase (		self: Optional[Any]					,   **_SCREAMING_SNAKE_CASE: Tuple		)       -> str:




              """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: Union[str, Any]					,   _SCREAMING_SNAKE_CASE: List[Any]					,   _SCREAMING_SNAKE_CASE: Optional[Any]=None					,   _SCREAMING_SNAKE_CASE: str="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
                            UpperCamelCase_          =  requests.get(_SCREAMING_SNAKE_CASE		).content
                     else:
                            with open(_SCREAMING_SNAKE_CASE					,   "rb"		) as f:
                                   UpperCamelCase_          =  f.read()

              if isinstance(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		):
                     UpperCamelCase_          =  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"		)

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

       def lowercase (		self: Optional[Any]					,   _SCREAMING_SNAKE_CASE: Tuple		)       -> Tuple:




              """simple docstring"""


              UpperCamelCase_          =  model_inputs.pop("candidate_labels"		)
              UpperCamelCase_          =  model_inputs.pop("text_inputs"		)
              if isinstance(text_inputs[0]					,   _SCREAMING_SNAKE_CASE		):
                     UpperCamelCase_          =  text_inputs[0]
              else:
                     # Batching case.
                     UpperCamelCase_          =  text_inputs[0][0]

              UpperCamelCase_          =  self.model(**_SCREAMING_SNAKE_CASE					,   **_SCREAMING_SNAKE_CASE		)

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



       def lowercase (		self: int					,   _SCREAMING_SNAKE_CASE: Any		)       -> Optional[Any]:




              """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(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)					,   key=lambda _SCREAMING_SNAKE_CASE		: -x[0]		)
              ]
              return result








import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate




def  lowerCAmelCase_ (							UpperCamelCase_  )     ->		Optional[int]:
       return x + 2







class 							_UpperCamelCase					(	unittest.TestCase     ):

       def lowercase (		self: Optional[int]		)       -> str:




              """simple docstring"""


              UpperCamelCase_          =  "x = 3"
              UpperCamelCase_          =  {}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              assert result == 3
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3}		)

              UpperCamelCase_          =  "x = y"
              UpperCamelCase_          =  {"y": 5}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              # evaluate returns the value of the last assignment.
              assert result == 5
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 5, "y": 5}		)

       def lowercase (		self: List[str]		)       -> Dict:




              """simple docstring"""


              UpperCamelCase_          =  "y = add_two(x)"
              UpperCamelCase_          =  {"x": 3}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {"add_two": add_two}					,   state=_SCREAMING_SNAKE_CASE		)
              assert result == 5
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "y": 5}		)

              # Won't work without the tool
              with CaptureStdout() as out:
                     UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              assert result is None
              assert "tried to execute add_two" in out.out

       def lowercase (		self: Union[str, Any]		)       -> str:




              """simple docstring"""


              UpperCamelCase_          =  "x = 3"
              UpperCamelCase_          =  {}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              assert result == 3
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3}		)

       def lowercase (		self: Dict		)       -> Any:




              """simple docstring"""


              UpperCamelCase_          =  "test_dict = {'x': x, 'y': add_two(x)}"
              UpperCamelCase_          =  {"x": 3}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {"add_two": add_two}					,   state=_SCREAMING_SNAKE_CASE		)
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "y": 5}		)
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "test_dict": {"x": 3, "y": 5}}		)

       def lowercase (		self: List[str]		)       -> Union[str, Any]:




              """simple docstring"""


              UpperCamelCase_          =  "x = 3\ny = 5"
              UpperCamelCase_          =  {}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              # evaluate returns the value of the last assignment.
              assert result == 5
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "y": 5}		)

       def lowercase (		self: List[Any]		)       -> int:




              """simple docstring"""


              UpperCamelCase_          =  "text = f'This is x: {x}.'"
              UpperCamelCase_          =  {"x": 3}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              # evaluate returns the value of the last assignment.
              assert result == "This is x: 3."
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "text": "This is x: 3."}		)

       def lowercase (		self: int		)       -> Union[str, Any]:




              """simple docstring"""


              UpperCamelCase_          =  "if x <= 3:\n    y = 2\nelse:\n    y = 5"
              UpperCamelCase_          =  {"x": 3}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              # evaluate returns the value of the last assignment.
              assert result == 2
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "y": 2}		)

              UpperCamelCase_          =  {"x": 8}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              # evaluate returns the value of the last assignment.
              assert result == 5
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 8, "y": 5}		)

       def lowercase (		self: str		)       -> Optional[Any]:




              """simple docstring"""


              UpperCamelCase_          =  "test_list = [x, add_two(x)]"
              UpperCamelCase_          =  {"x": 3}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {"add_two": add_two}					,   state=_SCREAMING_SNAKE_CASE		)
              self.assertListEqual(_SCREAMING_SNAKE_CASE					,   [3, 5]		)
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "test_list": [3, 5]}		)

       def lowercase (		self: List[str]		)       -> int:




              """simple docstring"""


              UpperCamelCase_          =  "y = x"
              UpperCamelCase_          =  {"x": 3}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {}					,   state=_SCREAMING_SNAKE_CASE		)
              assert result == 3
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "y": 3}		)

       def lowercase (		self: str		)       -> int:




              """simple docstring"""


              UpperCamelCase_          =  "test_list = [x, add_two(x)]\ntest_list[1]"
              UpperCamelCase_          =  {"x": 3}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {"add_two": add_two}					,   state=_SCREAMING_SNAKE_CASE		)
              assert result == 5
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "test_list": [3, 5]}		)

              UpperCamelCase_          =  "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
              UpperCamelCase_          =  {"x": 3}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {"add_two": add_two}					,   state=_SCREAMING_SNAKE_CASE		)
              assert result == 5
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 3, "test_dict": {"x": 3, "y": 5}}		)



       def lowercase (		self: Dict		)       -> Optional[int]:




              """simple docstring"""


              UpperCamelCase_          =  "x = 0\nfor i in range(3):\n    x = i"
              UpperCamelCase_          =  {}
              UpperCamelCase_          =  evaluate(_SCREAMING_SNAKE_CASE					,   {"range": range}					,   state=_SCREAMING_SNAKE_CASE		)
              assert result == 2
              self.assertDictEqual(_SCREAMING_SNAKE_CASE					,   {"x": 2, "i": 2}		)

