
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

lowerCamelCase_				:							str       =    logging.get_logger(__name__)
def        __lowercase(							__snake_case				:		bytes    ,__snake_case				:		int					)       ->   List[Any]:
       __snake_case						       =   f'''{sampling_rate}'''
       __snake_case						       =   '''1'''
       __snake_case						       =   '''f32le'''
       __snake_case						       =   [
           '''ffmpeg''',
           '''-i''',
           '''pipe:0''',
           '''-ac''',
           ac,
           '''-ar''',
           ar,
           '''-f''',
           format_for_conversion,
           '''-hide_banner''',
           '''-loglevel''',
           '''quiet''',
           '''pipe:1''',
       ]

       try:
              __snake_case						       =   subprocess.Popen(__A    ,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						       =   ffmpeg_process.communicate(__A					)
       __snake_case						       =   output_stream[0]

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







@add_end_docstrings(_lowerCamelCase					)
class  _lowerCamelCase			(_lowerCamelCase					):

     def __init__(  self							,       *SCREAMING_SNAKE_CASE_							,       **SCREAMING_SNAKE_CASE_    ):
            # Default, might be overriden by the model.config.
            __snake_case						       =   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							,       SCREAMING_SNAKE_CASE_							,       **SCREAMING_SNAKE_CASE_							,       ):
            return super().__call__(lowerCamelCase_							,       **lowerCamelCase_    )

     def 						__lowerCamelCase				(  self							,       SCREAMING_SNAKE_CASE_=None							,       **SCREAMING_SNAKE_CASE_    ):
            # No parameters on this pipeline right now
            __snake_case						       =   {}
            if top_k is not None:
                   if top_k > self.model.config.num_labels:
                          __snake_case						       =   self.model.config.num_labels
                   __snake_case						       =   top_k
            return {}, {}, postprocess_params

     def 						__lowerCamelCase				(  self							,       SCREAMING_SNAKE_CASE_    ):
            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
                          __snake_case						       =   requests.get(lowerCamelCase_    ).content
                   else:
                          with open(lowerCamelCase_							,       'rb'    ) as f:
                                 __snake_case						       =   f.read()

            if isinstance(lowerCamelCase_							,       lowerCamelCase_    ):
                   __snake_case						       =   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'    )

                   __snake_case						       =   inputs.pop('raw'							,       lowerCamelCase_    )
                   if _inputs is None:
                          # Remove path which will not be used from `datasets`.
                          inputs.pop('path'							,       lowerCamelCase_    )
                          __snake_case						       =   inputs.pop('array'							,       lowerCamelCase_    )
                   __snake_case						       =   inputs.pop('sampling_rate'    )
                   __snake_case						       =   _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						       =   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'    )

            __snake_case						       =   self.feature_extractor(
                lowerCamelCase_							,       sampling_rate=self.feature_extractor.sampling_rate							,       return_tensors='pt'    )
            return processed

     def 						__lowerCamelCase				(  self							,       SCREAMING_SNAKE_CASE_    ):
            __snake_case						       =   self.model(**lowerCamelCase_    )
            return model_outputs

     def 						__lowerCamelCase				(  self							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_=5    ):
            __snake_case						       =   model_outputs.logits[0].softmax(-1    )
            __snake_case						       =   probs.topk(lowerCamelCase_    )

            __snake_case						       =   scores.tolist()
            __snake_case						       =   ids.tolist()

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

            return labels






from typing import TYPE_CHECKING

from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available


__lowerCamelCase :    Tuple      						=      {
    '''configuration_utils''': ['''GenerationConfig'''],
    '''streamers''': ['''TextIteratorStreamer''', '''TextStreamer'''],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__lowerCamelCase :    Any      						=      [
	    '''Constraint''',
	    '''ConstraintListState''',
	    '''DisjunctiveConstraint''',
	    '''PhrasalConstraint''',
	]
	__lowerCamelCase :    int      						=      [
	    '''BeamHypotheses''',
	    '''BeamScorer''',
	    '''BeamSearchScorer''',
	    '''ConstrainedBeamSearchScorer''',
	]
	__lowerCamelCase :    Union[str, Any]      						=      [
	    '''EpsilonLogitsWarper''',
	    '''EtaLogitsWarper''',
	    '''ForcedBOSTokenLogitsProcessor''',
	    '''ForcedEOSTokenLogitsProcessor''',
	    '''HammingDiversityLogitsProcessor''',
	    '''InfNanRemoveLogitsProcessor''',
	    '''LogitsProcessor''',
	    '''LogitsProcessorList''',
	    '''LogitsWarper''',
	    '''MinLengthLogitsProcessor''',
	    '''MinNewTokensLengthLogitsProcessor''',
	    '''NoBadWordsLogitsProcessor''',
	    '''NoRepeatNGramLogitsProcessor''',
	    '''PrefixConstrainedLogitsProcessor''',
	    '''RepetitionPenaltyLogitsProcessor''',
	    '''SequenceBiasLogitsProcessor''',
	    '''EncoderRepetitionPenaltyLogitsProcessor''',
	    '''TemperatureLogitsWarper''',
	    '''TopKLogitsWarper''',
	    '''TopPLogitsWarper''',
	    '''TypicalLogitsWarper''',
	    '''EncoderNoRepeatNGramLogitsProcessor''',
	    '''ExponentialDecayLengthPenalty''',
	    '''LogitNormalization''',
	]
	__lowerCamelCase :    Union[str, Any]      						=      [
	    '''MaxNewTokensCriteria''',
	    '''MaxLengthCriteria''',
	    '''MaxTimeCriteria''',
	    '''StoppingCriteria''',
	    '''StoppingCriteriaList''',
	    '''validate_stopping_criteria''',
	]
	__lowerCamelCase :    Union[str, Any]      						=      [
	    '''GenerationMixin''',
	    '''top_k_top_p_filtering''',
	    '''GreedySearchEncoderDecoderOutput''',
	    '''GreedySearchDecoderOnlyOutput''',
	    '''SampleEncoderDecoderOutput''',
	    '''SampleDecoderOnlyOutput''',
	    '''BeamSearchEncoderDecoderOutput''',
	    '''BeamSearchDecoderOnlyOutput''',
	    '''BeamSampleEncoderDecoderOutput''',
	    '''BeamSampleDecoderOnlyOutput''',
	    '''ContrastiveSearchEncoderDecoderOutput''',
	    '''ContrastiveSearchDecoderOnlyOutput''',
	]

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__lowerCamelCase :    Tuple      						=      [
	    '''TFForcedBOSTokenLogitsProcessor''',
	    '''TFForcedEOSTokenLogitsProcessor''',
	    '''TFLogitsProcessor''',
	    '''TFLogitsProcessorList''',
	    '''TFLogitsWarper''',
	    '''TFMinLengthLogitsProcessor''',
	    '''TFNoBadWordsLogitsProcessor''',
	    '''TFNoRepeatNGramLogitsProcessor''',
	    '''TFRepetitionPenaltyLogitsProcessor''',
	    '''TFTemperatureLogitsWarper''',
	    '''TFTopKLogitsWarper''',
	    '''TFTopPLogitsWarper''',
	    '''TFForceTokensLogitsProcessor''',
	    '''TFSuppressTokensAtBeginLogitsProcessor''',
	    '''TFSuppressTokensLogitsProcessor''',
	]
	__lowerCamelCase :    Any      						=      [
	    '''TFGenerationMixin''',
	    '''tf_top_k_top_p_filtering''',
	    '''TFGreedySearchDecoderOnlyOutput''',
	    '''TFGreedySearchEncoderDecoderOutput''',
	    '''TFSampleEncoderDecoderOutput''',
	    '''TFSampleDecoderOnlyOutput''',
	    '''TFBeamSearchEncoderDecoderOutput''',
	    '''TFBeamSearchDecoderOnlyOutput''',
	    '''TFBeamSampleEncoderDecoderOutput''',
	    '''TFBeamSampleDecoderOnlyOutput''',
	    '''TFContrastiveSearchEncoderDecoderOutput''',
	    '''TFContrastiveSearchDecoderOnlyOutput''',
	]

try:
	if not is_flax_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__lowerCamelCase :    Optional[int]      						=      [
	    '''FlaxForcedBOSTokenLogitsProcessor''',
	    '''FlaxForcedEOSTokenLogitsProcessor''',
	    '''FlaxLogitsProcessor''',
	    '''FlaxLogitsProcessorList''',
	    '''FlaxLogitsWarper''',
	    '''FlaxMinLengthLogitsProcessor''',
	    '''FlaxTemperatureLogitsWarper''',
	    '''FlaxTopKLogitsWarper''',
	    '''FlaxTopPLogitsWarper''',
	]
	__lowerCamelCase :    Union[str, Any]      						=      [
	    '''FlaxGenerationMixin''',
	    '''FlaxGreedySearchOutput''',
	    '''FlaxSampleOutput''',
	    '''FlaxBeamSearchOutput''',
	]

if TYPE_CHECKING:
	from .configuration_utils import GenerationConfig
	from .streamers import TextIteratorStreamer, TextStreamer

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
		from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
		from .logits_process import (
		    EncoderNoRepeatNGramLogitsProcessor,
		    EncoderRepetitionPenaltyLogitsProcessor,
		    EpsilonLogitsWarper,
		    EtaLogitsWarper,
		    ExponentialDecayLengthPenalty,
		    ForcedBOSTokenLogitsProcessor,
		    ForcedEOSTokenLogitsProcessor,
		    HammingDiversityLogitsProcessor,
		    InfNanRemoveLogitsProcessor,
		    LogitNormalization,
		    LogitsProcessor,
		    LogitsProcessorList,
		    LogitsWarper,
		    MinLengthLogitsProcessor,
		    MinNewTokensLengthLogitsProcessor,
		    NoBadWordsLogitsProcessor,
		    NoRepeatNGramLogitsProcessor,
		    PrefixConstrainedLogitsProcessor,
		    RepetitionPenaltyLogitsProcessor,
		    SequenceBiasLogitsProcessor,
		    TemperatureLogitsWarper,
		    TopKLogitsWarper,
		    TopPLogitsWarper,
		    TypicalLogitsWarper,
		)
		from .stopping_criteria import (
		    MaxLengthCriteria,
		    MaxNewTokensCriteria,
		    MaxTimeCriteria,
		    StoppingCriteria,
		    StoppingCriteriaList,
		    validate_stopping_criteria,
		)
		from .utils import (
		    BeamSampleDecoderOnlyOutput,
		    BeamSampleEncoderDecoderOutput,
		    BeamSearchDecoderOnlyOutput,
		    BeamSearchEncoderDecoderOutput,
		    ContrastiveSearchDecoderOnlyOutput,
		    ContrastiveSearchEncoderDecoderOutput,
		    GenerationMixin,
		    GreedySearchDecoderOnlyOutput,
		    GreedySearchEncoderDecoderOutput,
		    SampleDecoderOnlyOutput,
		    SampleEncoderDecoderOutput,
		    top_k_top_p_filtering,
		)

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .tf_logits_process import (
		    TFForcedBOSTokenLogitsProcessor,
		    TFForcedEOSTokenLogitsProcessor,
		    TFForceTokensLogitsProcessor,
		    TFLogitsProcessor,
		    TFLogitsProcessorList,
		    TFLogitsWarper,
		    TFMinLengthLogitsProcessor,
		    TFNoBadWordsLogitsProcessor,
		    TFNoRepeatNGramLogitsProcessor,
		    TFRepetitionPenaltyLogitsProcessor,
		    TFSuppressTokensAtBeginLogitsProcessor,
		    TFSuppressTokensLogitsProcessor,
		    TFTemperatureLogitsWarper,
		    TFTopKLogitsWarper,
		    TFTopPLogitsWarper,
		)
		from .tf_utils import (
		    TFBeamSampleDecoderOnlyOutput,
		    TFBeamSampleEncoderDecoderOutput,
		    TFBeamSearchDecoderOnlyOutput,
		    TFBeamSearchEncoderDecoderOutput,
		    TFContrastiveSearchDecoderOnlyOutput,
		    TFContrastiveSearchEncoderDecoderOutput,
		    TFGenerationMixin,
		    TFGreedySearchDecoderOnlyOutput,
		    TFGreedySearchEncoderDecoderOutput,
		    TFSampleDecoderOnlyOutput,
		    TFSampleEncoderDecoderOutput,
		    tf_top_k_top_p_filtering,
		)

	try:
		if not is_flax_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .flax_logits_process import (
		    FlaxForcedBOSTokenLogitsProcessor,
		    FlaxForcedEOSTokenLogitsProcessor,
		    FlaxLogitsProcessor,
		    FlaxLogitsProcessorList,
		    FlaxLogitsWarper,
		    FlaxMinLengthLogitsProcessor,
		    FlaxTemperatureLogitsWarper,
		    FlaxTopKLogitsWarper,
		    FlaxTopPLogitsWarper,
		)
		from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
else:
	import sys

	__lowerCamelCase :    int      						=      _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



