

from datasets.utils.patching import _PatchedModuleObj, patch_submodule

from . import _test_patching
def 	a (     )       -> str:





      """simple docstring"""



      import os as original_os
      from os import path as original_path
      from os import rename as original_rename
      from os.path import dirname as original_dirname
      from os.path import join as original_join

      assert _test_patching.os is original_os
      assert _test_patching.path is original_path
      assert _test_patching.join is original_join

      assert _test_patching.renamed_os is original_os
      assert _test_patching.renamed_path is original_path
      assert _test_patching.renamed_join is original_join

      _lowercase      			='__test_patch_submodule_mock__'
      with patch_submodule(_test_patching ,  'os.path.join' ,  A__	):
            # Every way to access os.path.join must be patched, and the rest must stay untouched

            # check os.path.join
            assert isinstance(_test_patching.os ,  _PatchedModuleObj	)
            assert isinstance(_test_patching.os.path ,  _PatchedModuleObj	)
            assert _test_patching.os.path.join is mock

            # check path.join
            assert isinstance(_test_patching.path ,  _PatchedModuleObj	)
            assert _test_patching.path.join is mock

            # check join
            assert _test_patching.join is mock

            # check that the other attributes are untouched
            assert _test_patching.os.rename is original_rename
            assert _test_patching.path.dirname is original_dirname
            assert _test_patching.os.path.dirname is original_dirname

            # Even renamed modules or objects must be patched

            # check renamed_os.path.join
            assert isinstance(_test_patching.renamed_os ,  _PatchedModuleObj	)
            assert isinstance(_test_patching.renamed_os.path ,  _PatchedModuleObj	)
            assert _test_patching.renamed_os.path.join is mock

            # check renamed_path.join
            assert isinstance(_test_patching.renamed_path ,  _PatchedModuleObj	)
            assert _test_patching.renamed_path.join is mock

            # check renamed_join
            assert _test_patching.renamed_join is mock

            # check that the other attributes are untouched
            assert _test_patching.renamed_os.rename is original_rename
            assert _test_patching.renamed_path.dirname is original_dirname
            assert _test_patching.renamed_os.path.dirname is original_dirname

      # check that everthing is back to normal when the patch is over

      assert _test_patching.os is original_os
      assert _test_patching.path is original_path
      assert _test_patching.join is original_join

      assert _test_patching.renamed_os is original_os
      assert _test_patching.renamed_path is original_path
      assert _test_patching.renamed_join is original_join
def 	a (     )       -> List[Any]:





      """simple docstring"""



      assert _test_patching.open is open

      _lowercase      			='__test_patch_submodule_builtin_mock__'
      # _test_patching has "open" in its globals
      assert _test_patching.open is open
      with patch_submodule(_test_patching ,  'open' ,  A__	):
            assert _test_patching.open is mock

      # check that everthing is back to normal when the patch is over

      assert _test_patching.open is open
def 	a (     )       -> List[str]:





      """simple docstring"""



      _lowercase      			='__test_patch_submodule_missing_mock__'
      with patch_submodule(_test_patching ,  'pandas.read_csv' ,  A__	):
            pass
def 	a (     )       -> Dict:





      """simple docstring"""



      _lowercase      			='__test_patch_submodule_missing_builtin_mock__'
      # _test_patching doesn't have "len" in its globals
      assert getattr(_test_patching ,  'len' ,  A__	) is None
      with patch_submodule(_test_patching ,  'len' ,  A__	):
            assert _test_patching.len is mock
      assert _test_patching.len is len
def 	a (     )       -> Optional[Any]:





      """simple docstring"""



      _lowercase      			='__test_patch_submodule_start_and_stop_mock__'
      _lowercase      			=patch_submodule(_test_patching ,  'open' ,  A__	)
      assert _test_patching.open is open
      patch.start()
      assert _test_patching.open is mock
      patch.stop()
      assert _test_patching.open is open
def 	a (     )       -> Tuple:





      """simple docstring"""



      from os import rename as original_rename
      from os.path import dirname as original_dirname
      from os.path import join as original_join

      _lowercase      			='__test_patch_submodule_successive_join__'
      _lowercase      			='__test_patch_submodule_successive_dirname__'
      _lowercase      			='__test_patch_submodule_successive_rename__'
      assert _test_patching.os.path.join is original_join
      assert _test_patching.os.path.dirname is original_dirname
      assert _test_patching.os.rename is original_rename

      with patch_submodule(_test_patching ,  'os.path.join' ,  A__	):
            with patch_submodule(_test_patching ,  'os.rename' ,  A__	):
                  with patch_submodule(_test_patching ,  'os.path.dirname' ,  A__	):
                        assert _test_patching.os.path.join is mock_join
                        assert _test_patching.os.path.dirname is mock_dirname
                        assert _test_patching.os.rename is mock_rename

    # try another order
      with patch_submodule(_test_patching ,  'os.rename' ,  A__	):
            with patch_submodule(_test_patching ,  'os.path.join' ,  A__	):
                  with patch_submodule(_test_patching ,  'os.path.dirname' ,  A__	):
                        assert _test_patching.os.path.join is mock_join
                        assert _test_patching.os.path.dirname is mock_dirname
                        assert _test_patching.os.rename is mock_rename

      assert _test_patching.os.path.join is original_join
      assert _test_patching.os.path.dirname is original_dirname
      assert _test_patching.os.rename is original_rename







def 	a (     )       -> Optional[Any]:





      """simple docstring"""



      _lowercase      			='__test_patch_submodule_doesnt_exist_mock__'
      with patch_submodule(_test_patching ,  '__module_that_doesn_exist__.__attribute_that_doesn_exist__' ,  A__	):
            pass
      with patch_submodule(_test_patching ,  'os.__attribute_that_doesn_exist__' ,  A__	):
            pass





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


lowercase_   							=  logging.get_logger(__name__)





@add_end_docstrings(SCREAMING_SNAKE_CASE				)
class 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE				):




  def __init__(							self				,  **lowerCAmelCase   )    ->					Tuple:
        '''simple docstring'''






        super().__init__(**lowerCAmelCase   )

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




  def __call__(							self				,  lowerCAmelCase				,  **lowerCAmelCase   )    ->					int:
        '''simple docstring'''






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




  def     A__	(							self				,  **lowerCAmelCase   )    ->					Optional[Any]:
        '''simple docstring'''






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

        return preprocess_params, {}, {}




  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase=None				,  lowerCAmelCase="This is a sound of {}."   )    ->					Tuple:
        '''simple docstring'''






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

        if isinstance(lowerCAmelCase				,  lowerCAmelCase   ):
              _lowercase      			=ffmpeg_read(lowerCAmelCase				,  self.feature_extractor.sampling_rate   )

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

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




  def     A__	(							self				,  lowerCAmelCase   )    ->					Dict:
        '''simple docstring'''






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

        _lowercase      			=self.model(**lowerCAmelCase				,  **lowerCAmelCase   )

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




  def     A__	(							self				,  lowerCAmelCase   )    ->					Tuple:
        '''simple docstring'''






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

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

        _lowercase      			=[
            {'score': score, 'label': candidate_label}
            for score, candidate_label in sorted(zip(lowerCAmelCase				,  lowerCAmelCase   )				,  key=lambda lowerCAmelCase   : -x[0]   )
        ]
        return result


