


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

UpperCAmelCase			=    logging.get_logger(__name__)






def        __lowerCAmelCase    (SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE					)->  np.array:




      """simple docstring"""

      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(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'''					)
      snake_case_       =      ffmpeg_process.communicate(SCREAMING_SNAKE_CASE					)
      snake_case_       =      output_stream[0]

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







@add_end_docstrings(lowerCamelCase__       )
class lowerCAmelCase_						( lowerCamelCase__       ):

 '''simple docstring'''

 def __init__(	self		,      *_UpperCAmelCase		,      **_UpperCAmelCase					):
       # Default, might be overriden by the model.config.
       snake_case_       =      5
       super().__init__(*_UpperCAmelCase		,      **_UpperCAmelCase					)

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

       self.check_model_type(_UpperCAmelCase					)



 def __call__(	self		,      _UpperCAmelCase		,      **_UpperCAmelCase		,      ):
       return super().__call__(_UpperCAmelCase		,      **_UpperCAmelCase					)



 def 						UpperCamelCase__     (	self		,      _UpperCAmelCase=None		,      **_UpperCAmelCase					):
       # 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 						UpperCamelCase__     (	self		,      _UpperCAmelCase					):
       if isinstance(_UpperCAmelCase		,      _UpperCAmelCase					):
             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(_UpperCAmelCase					).content
             else:
                   with open(_UpperCAmelCase		,      '''rb'''					) as f:
                         snake_case_       =      f.read()

       if isinstance(_UpperCAmelCase		,      _UpperCAmelCase					):
             snake_case_       =      ffmpeg_read(_UpperCAmelCase		,      self.feature_extractor.sampling_rate					)

       if isinstance(_UpperCAmelCase		,      _UpperCAmelCase					):
             # 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'''		,      _UpperCAmelCase					)
             if _inputs is None:
                   # Remove path which will not be used from `datasets`.
                   inputs.pop('''path'''		,      _UpperCAmelCase					)
                   snake_case_       =      inputs.pop('''array'''		,      _UpperCAmelCase					)
             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(_UpperCAmelCase					)		,      _UpperCAmelCase		,      self.feature_extractor.sampling_rate					).numpy()

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



 def 						UpperCamelCase__     (	self		,      _UpperCAmelCase					):
       snake_case_       =      self.model(**_UpperCAmelCase					)
       return model_outputs





 def 						UpperCamelCase__     (	self		,      _UpperCAmelCase		,      _UpperCAmelCase=5					):
       snake_case_       =      model_outputs.logits[0].softmax(-1					)
       snake_case_       ,    snake_case_       =      probs.topk(_UpperCAmelCase					)

       snake_case_       =      scores.tolist()
       snake_case_       =      ids.tolist()

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

       return labels



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCAmelCase			=    {
    """configuration_big_bird""": ["""BIG_BIRD_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BigBirdConfig""", """BigBirdOnnxConfig"""],
}

try:
   if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   UpperCAmelCase			=    ["""BigBirdTokenizer"""]

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   UpperCAmelCase			=    ["""BigBirdTokenizerFast"""]

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   UpperCAmelCase			=    [
       """BIG_BIRD_PRETRAINED_MODEL_ARCHIVE_LIST""",
       """BigBirdForCausalLM""",
       """BigBirdForMaskedLM""",
       """BigBirdForMultipleChoice""",
       """BigBirdForPreTraining""",
       """BigBirdForQuestionAnswering""",
       """BigBirdForSequenceClassification""",
       """BigBirdForTokenClassification""",
       """BigBirdLayer""",
       """BigBirdModel""",
       """BigBirdPreTrainedModel""",
       """load_tf_weights_in_big_bird""",
   ]

try:
   if not is_flax_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   UpperCAmelCase			=    [
       """FlaxBigBirdForCausalLM""",
       """FlaxBigBirdForMaskedLM""",
       """FlaxBigBirdForMultipleChoice""",
       """FlaxBigBirdForPreTraining""",
       """FlaxBigBirdForQuestionAnswering""",
       """FlaxBigBirdForSequenceClassification""",
       """FlaxBigBirdForTokenClassification""",
       """FlaxBigBirdModel""",
       """FlaxBigBirdPreTrainedModel""",
   ]

if TYPE_CHECKING:
   from .configuration_big_bird import BIG_BIRD_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdConfig, BigBirdOnnxConfig

   try:
      if not is_sentencepiece_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_big_bird import BigBirdTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_big_bird_fast import BigBirdTokenizerFast

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_big_bird import (
          BIG_BIRD_PRETRAINED_MODEL_ARCHIVE_LIST,
          BigBirdForCausalLM,
          BigBirdForMaskedLM,
          BigBirdForMultipleChoice,
          BigBirdForPreTraining,
          BigBirdForQuestionAnswering,
          BigBirdForSequenceClassification,
          BigBirdForTokenClassification,
          BigBirdLayer,
          BigBirdModel,
          BigBirdPreTrainedModel,
          load_tf_weights_in_big_bird,
      )

   try:
      if not is_flax_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_flax_big_bird import (
          FlaxBigBirdForCausalLM,
          FlaxBigBirdForMaskedLM,
          FlaxBigBirdForMultipleChoice,
          FlaxBigBirdForPreTraining,
          FlaxBigBirdForQuestionAnswering,
          FlaxBigBirdForSequenceClassification,
          FlaxBigBirdForTokenClassification,
          FlaxBigBirdModel,
          FlaxBigBirdPreTrainedModel,
      )

else:
   import sys

   UpperCAmelCase			=    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)