




"""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

_lowercase						   =     logging.get_logger(__name__)

def 		lowerCAmelCase				(			lowerCamelCase   ,      lowerCamelCase		):
						'''simple docstring'''


						snake_case__							:       Dict				      =       f'''{sampling_rate}'''
						snake_case__							:       Optional[Any]				      =       '''1'''
						snake_case__							:       Any				      =       '''f32le'''
						snake_case__							:       List[Any]				      =       [
						    '''ffmpeg''',
						    '''-i''',
						    '''pipe:0''',
						    '''-ac''',
						    ac,
						    '''-ar''',
						    ar,
						    '''-f''',
						    format_for_conversion,
						    '''-hide_banner''',
						    '''-loglevel''',
						    '''quiet''',
						    '''pipe:1''',
						]

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

						snake_case__							:       List[Any]				      =       np.frombuffer(lowerCamelCase   ,      np.floataa		)
						if audio.shape[0] == 0:
												raise ValueError('''Malformed soundfile'''		)
						return audio

@add_end_docstrings(snake_case_						)
class    __lowercase							(      snake_case_						):


				'''simple docstring'''


				def __init__( self :  List[Any]   ,*SCREAMING_SNAKE_CASE_ :  Dict   ,**SCREAMING_SNAKE_CASE_ :  List[str]   ):
										# Default, might be overriden by the model.config.
										snake_case__							:       List[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 :  int   ,SCREAMING_SNAKE_CASE_ :  Union[np.ndarray, bytes, str]   ,**SCREAMING_SNAKE_CASE_ :  Optional[int]   ,):
										return super().__call__(SCREAMING_SNAKE_CASE_   ,**SCREAMING_SNAKE_CASE_   )

				def    _lowerCamelCase       ( self :  str   ,SCREAMING_SNAKE_CASE_ :  List[Any]=None   ,**SCREAMING_SNAKE_CASE_ :  str   ):
										# No parameters on this pipeline right now
										snake_case__							:       Optional[Any]				      =       {}
										if top_k is not None:
																if top_k > self.model.config.num_labels:
																						snake_case__							:       List[str]				      =       self.model.config.num_labels
																snake_case__							:       Tuple				      =       top_k
										return {}, {}, postprocess_params

				def    _lowerCamelCase       ( self :  List[Any]   ,SCREAMING_SNAKE_CASE_ :  Optional[Any]   ):
										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
																						snake_case__							:       str				      =       requests.get(SCREAMING_SNAKE_CASE_   ).content
																else:
																						with open(SCREAMING_SNAKE_CASE_   ,'''rb'''   ) as f:
																												snake_case__							:       str				      =       f.read()

										if isinstance(SCREAMING_SNAKE_CASE_   ,SCREAMING_SNAKE_CASE_   ):
																snake_case__							:       Optional[Any]				      =       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'''   )

																snake_case__							:       int				      =       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_   )
																						snake_case__							:       List[Any]				      =       inputs.pop('''array'''   ,SCREAMING_SNAKE_CASE_   )
																snake_case__							:       Optional[Any]				      =       inputs.pop('''sampling_rate'''   )
																snake_case__							:       List[str]				      =       _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`.'''   )

																						snake_case__							:       List[str]				      =       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'''   )

										snake_case__							:       List[Any]				      =       self.feature_extractor(
										    SCREAMING_SNAKE_CASE_   ,sampling_rate=self.feature_extractor.sampling_rate   ,return_tensors='''pt'''   )
										return processed

				def    _lowerCamelCase       ( self :  Tuple   ,SCREAMING_SNAKE_CASE_ :  List[str]   ):
										snake_case__							:       List[str]				      =       self.model(**SCREAMING_SNAKE_CASE_   )
										return model_outputs





				def    _lowerCamelCase       ( self :  Union[str, Any]   ,SCREAMING_SNAKE_CASE_ :  Optional[Any]   ,SCREAMING_SNAKE_CASE_ :  int=5   ):
										snake_case__							:       Tuple				      =       model_outputs.logits[0].softmax(-1   )
										snake_case__      ,						snake_case__							:       Optional[Any]				      =       probs.topk(SCREAMING_SNAKE_CASE_   )

										snake_case__							:       Any				      =       scores.tolist()
										snake_case__							:       Tuple				      =       ids.tolist()

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

										return labels








"""simple docstring"""





from __future__ import annotations

from enum import Enum, unique
from typing import TypeVar

# Create a generic variable that can be 'Enum', or any subclass.
_lowercase						   =     TypeVar("""T""", bound="""Enum""")

@unique
class    __lowercase							(      snake_case_						):


				'''simple docstring'''


				_lowerCAmelCase						      =80
				_lowerCAmelCase						      =70
				_lowerCAmelCase						      =60
				_lowerCAmelCase						      =50
				_lowerCAmelCase						      =40
				_lowerCAmelCase						      =30
				_lowerCAmelCase						      =20
				_lowerCAmelCase						      =10







@unique
class    __lowercase							(      snake_case_						):


				'''simple docstring'''


				_lowerCAmelCase						      =24
				_lowerCAmelCase						      =21
				_lowerCAmelCase						      =18
				_lowerCAmelCase						      =15
				_lowerCAmelCase						      =12
				_lowerCAmelCase						      =9
				_lowerCAmelCase						      =6
				_lowerCAmelCase						      =3
				_lowerCAmelCase						      =2
				_lowerCAmelCase						      =1
				_lowerCAmelCase						      =-1
				_lowerCAmelCase						      =-2
				_lowerCAmelCase						      =-3
				_lowerCAmelCase						      =-6
				_lowerCAmelCase						      =-9
				_lowerCAmelCase						      =-12
				_lowerCAmelCase						      =-15
				_lowerCAmelCase						      =-18
				_lowerCAmelCase						      =-21
				_lowerCAmelCase						      =-24

				@classmethod
				def    _lowerCamelCase       ( cls :  type[T]   ):
										return {unit.name: unit.value for unit in cls if unit.value > 0}





				@classmethod
				def    _lowerCamelCase       ( cls :  type[T]   ):
										return {unit.name: unit.value for unit in cls if unit.value < 0}







def 		lowerCAmelCase				(			lowerCamelCase		):
						'''simple docstring'''


						snake_case__							:       List[Any]				      =       SIUnit.get_positive() if value > 0 else SIUnit.get_negative()
						for name_prefix, value_prefix in prefixes.items():
												snake_case__							:       Optional[int]				      =       value / (10**value_prefix)
												if numerical_part > 1:
																		return f'''{numerical_part!s} {name_prefix}'''
						return str(lowerCamelCase		)

def 		lowerCAmelCase				(			lowerCamelCase		):
						'''simple docstring'''


						for prefix in BinaryUnit:
												snake_case__							:       int				      =       value / (2**prefix.value)
												if numerical_part > 1:
																		return f'''{numerical_part!s} {prefix.name}'''
						return str(lowerCamelCase		)


if __name__ == "__main__":
							import doctest

							doctest.testmod()


