code: 
  
  
  
  
  import subprocess
  from typing import Union
  
  import numpy as np
  import requests
  
  from ..utils import add_end_docstrings, is_torch_available, is_torchaudio_available, logging
  from .base import PIPELINE_INIT_ARGS, Pipeline
  
  
  if is_torch_available():
   from ..models.auto.modeling_auto import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
  
  __snake_case							      =						logging.get_logger(__name__)
  
  
  def 						_A     (       SCREAMING_SNAKE_CASE__						:			bytes  ,						SCREAMING_SNAKE_CASE__						:			int ):
      UpperCamelCase :Any										=     F'''{sampling_rate}'''
      UpperCamelCase :Dict										=     '''1'''
      UpperCamelCase :int										=     '''f32le'''
      UpperCamelCase :int										=     [
          '''ffmpeg''',
          '''-i''',
          '''pipe:0''',
          '''-ac''',
          ac,
          '''-ar''',
          ar,
          '''-f''',
          format_for_conversion,
          '''-hide_banner''',
          '''-loglevel''',
          '''quiet''',
          '''pipe:1''',
      ]
  
      try:
          UpperCamelCase :Optional[int]										=     subprocess.Popen(SCREAMING_SNAKE_CASE__  ,						stdin=subprocess.PIPE  ,						stdout=subprocess.PIPE )
      except FileNotFoundError:
          raise ValueError('''ffmpeg was not found but is required to load audio files from filename''' )
      UpperCamelCase :int										=     ffmpeg_process.communicate(SCREAMING_SNAKE_CASE__ )
      UpperCamelCase :int										=     output_stream[0]
  
      UpperCamelCase :Dict										=     np.frombuffer(SCREAMING_SNAKE_CASE__  ,						np.floataa )
      if audio.shape[0] == 0:
          raise ValueError('''Malformed soundfile''' )
      return audio
  
  
  
  
  
  
  
  @add_end_docstrings(lowercase				)
  class     UpperCAmelCase_		(      lowercase				):
  
  
  
        """simple docstring"""
        def __init__(       self					,       *SCREAMING_SNAKE_CASE_					,       **SCREAMING_SNAKE_CASE_				)       ->   Optional[Any]:
            # Default, might be overriden by the model.config.
            UpperCamelCase :Any										=     5
            super().__init__(*SCREAMING_SNAKE_CASE_					,       **SCREAMING_SNAKE_CASE_				)
  
            if self.framework != "pt":
                raise ValueError(F'''The {self.__class__} is only available in PyTorch.'''				)
  
            self.check_model_type(SCREAMING_SNAKE_CASE_				)
        def __call__(       self					,       SCREAMING_SNAKE_CASE_					,       **SCREAMING_SNAKE_CASE_					,       )       ->   int:
            return super().__call__(SCREAMING_SNAKE_CASE_					,       **SCREAMING_SNAKE_CASE_				)
        def 					UpperCAmelCase		(       self					,       SCREAMING_SNAKE_CASE_=None					,       **SCREAMING_SNAKE_CASE_				)       ->   List[str]:
            # No parameters on this pipeline right now
            UpperCamelCase :Optional[int]										=     {}
            if top_k is not None:
                if top_k > self.model.config.num_labels:
                    UpperCamelCase :List[str]										=     self.model.config.num_labels
                UpperCamelCase :Dict										=     top_k
            return {}, {}, postprocess_params
        def 					UpperCAmelCase		(       self					,       SCREAMING_SNAKE_CASE_				)       ->   Tuple:
            if isinstance(SCREAMING_SNAKE_CASE_					,       SCREAMING_SNAKE_CASE_				):
                if inputs.startswith('''http://'''				) or inputs.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 :List[str]										=     requests.get(SCREAMING_SNAKE_CASE_				).content
                else:
                    with open(SCREAMING_SNAKE_CASE_					,       '''rb'''				) as f:
                        UpperCamelCase :Any										=     f.read()
  
            if isinstance(SCREAMING_SNAKE_CASE_					,       SCREAMING_SNAKE_CASE_				):
                UpperCamelCase :Dict										=     ffmpeg_read(SCREAMING_SNAKE_CASE_					,       self.feature_extractor.sampling_rate				)
  
            if isinstance(SCREAMING_SNAKE_CASE_					,       SCREAMING_SNAKE_CASE_				):
                # Accepting `"array"` which is the key defined in `datasets` for
                # better integration
                if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
                    raise ValueError(
                        '''When passing a dictionary to AudioClassificationPipeline, the dict needs to contain a '''
                        '''"raw" key containing the numpy array representing the audio and a "sampling_rate" key, '''
                        '''containing the sampling_rate associated with that array'''				)
  
                UpperCamelCase :Union[str, Any]										=     inputs.pop('''raw'''					,       SCREAMING_SNAKE_CASE_				)
                if _inputs is None:
                    # Remove path which will not be used from `datasets`.
                    inputs.pop('''path'''					,       SCREAMING_SNAKE_CASE_				)
                    UpperCamelCase :int										=     inputs.pop('''array'''					,       SCREAMING_SNAKE_CASE_				)
                UpperCamelCase :Tuple										=     inputs.pop('''sampling_rate'''				)
                UpperCamelCase :Tuple										=     _inputs
                if in_sampling_rate != self.feature_extractor.sampling_rate:
                    import torch
  
                    if is_torchaudio_available():
                        from torchaudio import functional as F
                    else:
                        raise ImportError(
                            '''torchaudio is required to resample audio samples in AudioClassificationPipeline. '''
                            '''The torchaudio package can be installed through: `pip install torchaudio`.'''				)
  
                    UpperCamelCase :int										=     F.resample(
                        torch.from_numpy(SCREAMING_SNAKE_CASE_				)					,       SCREAMING_SNAKE_CASE_					,       self.feature_extractor.sampling_rate				).numpy()
  
            if not isinstance(SCREAMING_SNAKE_CASE_					,       np.ndarray				):
                raise ValueError('''We expect a numpy ndarray as input'''				)
            if len(inputs.shape				) != 1:
                raise ValueError('''We expect a single channel audio input for AudioClassificationPipeline'''				)
  
            UpperCamelCase :Union[str, Any]										=     self.feature_extractor(
                SCREAMING_SNAKE_CASE_					,       sampling_rate=self.feature_extractor.sampling_rate					,       return_tensors='''pt'''				)
            return processed
        def 					UpperCAmelCase		(       self					,       SCREAMING_SNAKE_CASE_				)       ->   List[Any]:
            UpperCamelCase :List[Any]										=     self.model(**SCREAMING_SNAKE_CASE_				)
            return model_outputs
  
  
  
  
        def 					UpperCAmelCase		(       self					,       SCREAMING_SNAKE_CASE_					,       SCREAMING_SNAKE_CASE_=5				)       ->   Optional[int]:
            UpperCamelCase :List[str]										=     model_outputs.logits[0].softmax(-1				)
            UpperCamelCase :str										=     probs.topk(SCREAMING_SNAKE_CASE_				)
  
            UpperCamelCase :List[Any]										=     scores.tolist()
            UpperCamelCase :Union[str, Any]										=     ids.tolist()
  
            UpperCamelCase :List[str]										=     [{'''score''': score, '''label''': self.model.config.idalabel[_id]} for score, _id in zip(SCREAMING_SNAKE_CASE_					,       SCREAMING_SNAKE_CASE_				)]
  
            return labels
  
  
  
  
  
  
style_context: 
  
  
  
  
  
  
  from __future__ import annotations
  
  from typing import Generic, TypeVar
  
  __snake_case							      =						TypeVar("""T""")
  
  
  
  
  
  
  
  class     UpperCAmelCase_		(      lowercase				):
  
  
  
        """simple docstring"""
        pass
  
  
  
  
  
  
  
  class     UpperCAmelCase_		(      lowercase				):
  
  
  
        """simple docstring"""
        pass
  
  
  
  
  
  
  
  class     UpperCAmelCase_		(      Generic[T]				):
  
  
  
        """simple docstring"""
        def __init__(       self					,       SCREAMING_SNAKE_CASE_ = 10				)       ->   List[str]:
            UpperCamelCase :list[T]										=     []
            UpperCamelCase :Any										=     limit
        def __bool__(       self				)       ->   bool:
            return bool(self.stack				)
        def __str__(       self				)       ->   str:
            return str(self.stack				)
        def 					UpperCAmelCase		(       self					,       SCREAMING_SNAKE_CASE_				)       ->   None:
            if len(self.stack				) >= self.limit:
                raise StackOverflowError
            self.stack.append(SCREAMING_SNAKE_CASE_				)
        def 					UpperCAmelCase		(       self				)       ->   T:
            if not self.stack:
                raise StackUnderflowError
            return self.stack.pop()
        def 					UpperCAmelCase		(       self				)       ->   T:
            if not self.stack:
                raise StackUnderflowError
            return self.stack[-1]
        def 					UpperCAmelCase		(       self				)       ->   bool:
            return not bool(self.stack				)
        def 					UpperCAmelCase		(       self				)       ->   bool:
            return self.size() == self.limit
        def 					UpperCAmelCase		(       self				)       ->   int:
            return len(self.stack				)
  
  
  
  
        def __contains__(       self					,       SCREAMING_SNAKE_CASE_				)       ->   bool:
            return item in self.stack
  
  
  
  
  
  
  
  def 						_A     (       ):
      UpperCamelCase :Stack[int]										=     Stack(10 )
      assert bool(SCREAMING_SNAKE_CASE__ ) is False
      assert stack.is_empty() is True
      assert stack.is_full() is False
      assert str(SCREAMING_SNAKE_CASE__ ) == "[]"
  
      try:
          UpperCamelCase :Optional[int]										=     stack.pop()
          raise AssertionError  # This should not happen
      except StackUnderflowError:
          assert True  # This should happen
  
      try:
          UpperCamelCase :Union[str, Any]										=     stack.peek()
          raise AssertionError  # This should not happen
      except StackUnderflowError:
          assert True  # This should happen
  
      for i in range(10 ):
          assert stack.size() == i
          stack.push(SCREAMING_SNAKE_CASE__ )
  
      assert bool(SCREAMING_SNAKE_CASE__ )
      assert not stack.is_empty()
      assert stack.is_full()
      assert str(SCREAMING_SNAKE_CASE__ ) == str(list(range(10 ) ) )
      assert stack.pop() == 9
      assert stack.peek() == 8
  
      stack.push(100 )
      assert str(SCREAMING_SNAKE_CASE__ ) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100] )
  
      try:
          stack.push(200 )
          raise AssertionError  # This should not happen
      except StackOverflowError:
          assert True  # This should happen
  
      assert not stack.is_empty()
      assert stack.size() == 10
  
      assert 5 in stack
      assert 55 not in stack
  
  
  if __name__ == "__main__":
   test_stack()
  
  
  
  
  
  