




"""simple docstring"""







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

SCREAMING_SNAKE_CASE_      =					logging.get_logger(__name__)





def     __snake_case   (							_lowercase ,_lowercase						):


    """simple docstring"""







    UpperCamelCase										=  f'{sampling_rate}'
    UpperCamelCase										=  '''1'''
    UpperCamelCase										=  '''f32le'''
    UpperCamelCase										=  [
        '''ffmpeg''',
        '''-i''',
        '''pipe:0''',
        '''-ac''',
        ac,
        '''-ar''',
        ar,
        '''-f''',
        format_for_conversion,
        '''-hide_banner''',
        '''-loglevel''',
        '''quiet''',
        '''pipe:1''',
    ]

    try:
        UpperCamelCase										=  subprocess.Popen(_lowercase ,stdin=subprocess.PIPE ,stdout=subprocess.PIPE						)
    except FileNotFoundError:
        raise ValueError('''ffmpeg was not found but is required to load audio files from filename'''						)
    UpperCamelCase										=  ffmpeg_process.communicate(_lowercase						)
    UpperCamelCase										=  output_stream[0]

    UpperCamelCase										=  np.frombuffer(_lowercase ,np.floataa						)
    if audio.shape[0] == 0:
        raise ValueError('''Malformed soundfile'''						)
    return audio


@add_end_docstrings(lowerCamelCase_ )
class 							snake_case_ (				lowerCamelCase_ ):







   """simple docstring"""




   def __init__(		self					,				*lowerCamelCase_					,				**lowerCamelCase_)							->      List[Any]:
       # Default, might be overriden by the model.config.
       UpperCamelCase										=  5
       super().__init__(*lowerCamelCase_					,				**lowerCamelCase_)

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

       self.check_model_type(lowerCamelCase_)







   def __call__(		self					,				lowerCamelCase_					,				**lowerCamelCase_					,				)							->      Optional[int]:
       return super().__call__(lowerCamelCase_					,				**lowerCamelCase_)







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_=None					,				**lowerCamelCase_)							->      str:
       # No parameters on this pipeline right now
       UpperCamelCase										=  {}
       if top_k is not None:
           if top_k > self.model.config.num_labels:
               UpperCamelCase										=  self.model.config.num_labels
           UpperCamelCase										=  top_k
       return {}, {}, postprocess_params







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_)							->      str:
       if isinstance(lowerCamelCase_					,				lowerCamelCase_):
           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										=  requests.get(lowerCamelCase_).content
           else:
               with open(lowerCamelCase_					,				'''rb''') as f:
                   UpperCamelCase										=  f.read()

       if isinstance(lowerCamelCase_					,				lowerCamelCase_):
           UpperCamelCase										=  ffmpeg_read(lowerCamelCase_					,				self.feature_extractor.sampling_rate)

       if isinstance(lowerCamelCase_					,				lowerCamelCase_):
           # 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										=  inputs.pop('''raw'''					,				lowerCamelCase_)
           if _inputs is None:
               # Remove path which will not be used from `datasets`.
               inputs.pop('''path'''					,				lowerCamelCase_)
               UpperCamelCase										=  inputs.pop('''array'''					,				lowerCamelCase_)
           UpperCamelCase										=  inputs.pop('''sampling_rate''')
           UpperCamelCase										=  _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										=  F.resample(
                   torch.from_numpy(lowerCamelCase_)					,				lowerCamelCase_					,				self.feature_extractor.sampling_rate).numpy()

       if not isinstance(lowerCamelCase_					,				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										=  self.feature_extractor(
           lowerCamelCase_					,				sampling_rate=self.feature_extractor.sampling_rate					,				return_tensors='''pt''')
       return processed







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_)							->      Tuple:
       UpperCamelCase										=  self.model(**lowerCamelCase_)
       return model_outputs







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_=5)							->      List[str]:
       UpperCamelCase										=  model_outputs.logits[0].softmax(-1)
       UpperCamelCase					,  UpperCamelCase										=  probs.topk(lowerCamelCase_)

       UpperCamelCase										=  scores.tolist()
       UpperCamelCase										=  ids.tolist()

       UpperCamelCase										=  [{'''score''': score, '''label''': self.model.config.idalabel[_id]} for score, _id in zip(lowerCamelCase_					,				lowerCamelCase_)]

       return labels





"""simple docstring"""







from math import pi





def     __snake_case   (							_lowercase						):


    """simple docstring"""







    return degree / (180 / pi)


if __name__ == "__main__":
  from doctest import testmod

  testmod()