





'''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__		:    Tuple =       logging.get_logger(__name__)







def       a__       (       lowercase      :  bytes,      lowercase      :  int   )	->	np.array:





     """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(__magic_name__				)
class        __lowerCAmelCase  (					__magic_name__				):






       """simple docstring"""





       def __init__(							self     :	str ,				*lowerCAmelCase__     :	List[Any] ,				**lowerCAmelCase__     :	str  )					->  Optional[int]:

            '''simple docstring'''




            _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     :	Any ,				lowerCAmelCase__     :	Union[np.ndarray, bytes, str] ,				**lowerCAmelCase__     :	str ,				)					->  Dict:

            '''simple docstring'''




            return super().__call__(lowerCAmelCase__ ,				**lowerCAmelCase__  )





       def snake_case__		(							self     :	Union[str, Any] ,				lowerCAmelCase__     :	Union[str, Any]=None ,				**lowerCAmelCase__     :	List[str]  )					->  str:

            '''simple docstring'''




            _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 snake_case__		(							self     :	Optional[int] ,				lowerCAmelCase__     :	Optional[int]  )					->  Dict:

            '''simple docstring'''




            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 snake_case__		(							self     :	Union[str, Any] ,				lowerCAmelCase__     :	Union[str, Any]  )					->  Any:

            '''simple docstring'''




            _UpperCamelCase       					= self.model(**lowerCAmelCase__  )
            return model_outputs







       def snake_case__		(							self     :	int ,				lowerCAmelCase__     :	Union[str, Any] ,				lowerCAmelCase__     :	List[str]=5  )					->  Optional[Any]:

            '''simple docstring'''




            _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 ..utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_librosa_available,
    is_note_seq_available,
    is_onnx_available,
    is_torch_available,
    is_transformers_available,
)


try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_pt_objects import *  # noqa F403
else:
   from .consistency_models import ConsistencyModelPipeline
   from .dance_diffusion import DanceDiffusionPipeline
   from .ddim import DDIMPipeline
   from .ddpm import DDPMPipeline
   from .dit import DiTPipeline
   from .latent_diffusion import LDMSuperResolutionPipeline
   from .latent_diffusion_uncond import LDMPipeline
   from .pipeline_utils import AudioPipelineOutput, DiffusionPipeline, ImagePipelineOutput
   from .pndm import PNDMPipeline
   from .repaint import RePaintPipeline
   from .score_sde_ve import ScoreSdeVePipeline
   from .stochastic_karras_ve import KarrasVePipeline

try:
   if not (is_torch_available() and is_librosa_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_torch_and_librosa_objects import *  # noqa F403
else:
   from .audio_diffusion import AudioDiffusionPipeline, Mel

try:
   if not (is_torch_available() and is_transformers_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
   from .alt_diffusion import AltDiffusionImgaImgPipeline, AltDiffusionPipeline
   from .audioldm import AudioLDMPipeline
   from .controlnet import (
       StableDiffusionControlNetImgaImgPipeline,
       StableDiffusionControlNetInpaintPipeline,
       StableDiffusionControlNetPipeline,
   )
   from .deepfloyd_if import (
       IFImgaImgPipeline,
       IFImgaImgSuperResolutionPipeline,
       IFInpaintingPipeline,
       IFInpaintingSuperResolutionPipeline,
       IFPipeline,
       IFSuperResolutionPipeline,
   )
   from .kandinsky import (
       KandinskyImgaImgPipeline,
       KandinskyInpaintPipeline,
       KandinskyPipeline,
       KandinskyPriorPipeline,
   )
   from .kandinskya_a import (
       KandinskyVaaControlnetImgaImgPipeline,
       KandinskyVaaControlnetPipeline,
       KandinskyVaaImgaImgPipeline,
       KandinskyVaaInpaintPipeline,
       KandinskyVaaPipeline,
       KandinskyVaaPriorEmbaEmbPipeline,
       KandinskyVaaPriorPipeline,
   )
   from .latent_diffusion import LDMTextToImagePipeline
   from .paint_by_example import PaintByExamplePipeline
   from .semantic_stable_diffusion import SemanticStableDiffusionPipeline
   from .shap_e import ShapEImgaImgPipeline, ShapEPipeline
   from .stable_diffusion import (
       CycleDiffusionPipeline,
       StableDiffusionAttendAndExcitePipeline,
       StableDiffusionDepthaImgPipeline,
       StableDiffusionDiffEditPipeline,
       StableDiffusionImageVariationPipeline,
       StableDiffusionImgaImgPipeline,
       StableDiffusionInpaintPipeline,
       StableDiffusionInpaintPipelineLegacy,
       StableDiffusionInstructPixaPixPipeline,
       StableDiffusionLatentUpscalePipeline,
       StableDiffusionLDMaDPipeline,
       StableDiffusionModelEditingPipeline,
       StableDiffusionPanoramaPipeline,
       StableDiffusionParadigmsPipeline,
       StableDiffusionPipeline,
       StableDiffusionPixaPixZeroPipeline,
       StableDiffusionSAGPipeline,
       StableDiffusionUpscalePipeline,
       StableUnCLIPImgaImgPipeline,
       StableUnCLIPPipeline,
   )
   from .stable_diffusion_safe import StableDiffusionPipelineSafe
   from .text_to_video_synthesis import TextToVideoSDPipeline, TextToVideoZeroPipeline, VideoToVideoSDPipeline
   from .unclip import UnCLIPImageVariationPipeline, UnCLIPPipeline
   from .unidiffuser import ImageTextPipelineOutput, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder
   from .versatile_diffusion import (
       VersatileDiffusionDualGuidedPipeline,
       VersatileDiffusionImageVariationPipeline,
       VersatileDiffusionPipeline,
       VersatileDiffusionTextToImagePipeline,
   )
   from .vq_diffusion import VQDiffusionPipeline


try:
   if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_torch_and_transformers_and_invisible_watermark_objects import *  # noqa F403
else:
   from .stable_diffusion_xl import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline

try:
   if not is_onnx_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_onnx_objects import *  # noqa F403
else:
   from .onnx_utils import OnnxRuntimeModel

try:
   if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_torch_and_transformers_and_onnx_objects import *  # noqa F403
else:
   from .stable_diffusion import (
       OnnxStableDiffusionImgaImgPipeline,
       OnnxStableDiffusionInpaintPipeline,
       OnnxStableDiffusionInpaintPipelineLegacy,
       OnnxStableDiffusionPipeline,
       OnnxStableDiffusionUpscalePipeline,
       StableDiffusionOnnxPipeline,
   )

try:
   if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
   from .stable_diffusion import StableDiffusionKDiffusionPipeline

try:
   if not is_flax_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_flax_objects import *  # noqa F403
else:
   from .pipeline_flax_utils import FlaxDiffusionPipeline


try:
   if not (is_flax_available() and is_transformers_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_flax_and_transformers_objects import *  # noqa F403
else:
   from .controlnet import FlaxStableDiffusionControlNetPipeline
   from .stable_diffusion import (
       FlaxStableDiffusionImgaImgPipeline,
       FlaxStableDiffusionInpaintPipeline,
       FlaxStableDiffusionPipeline,
   )
try:
   if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_transformers_and_torch_and_note_seq_objects import *  # noqa F403
else:
   from .spectrogram_diffusion import MidiProcessor, SpectrogramDiffusionPipeline



