code: 
  
  
  '''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__				:    Any         =    logging.get_logger(__name__)
  
  
  
  
  def       a__						(		snake_case__				:       bytes	,      snake_case__				:       int    ):
    _UpperCAmelCase		:       List[Any]       =    f'''{sampling_rate}'''
    _UpperCAmelCase		:       List[str]       =    """1"""
    _UpperCAmelCase		:       Union[str, Any]       =    """f32le"""
    _UpperCAmelCase		:       Dict       =    [
        """ffmpeg""",
        """-i""",
        """pipe:0""",
        """-ac""",
        ac,
        """-ar""",
        ar,
        """-f""",
        format_for_conversion,
        """-hide_banner""",
        """-loglevel""",
        """quiet""",
        """pipe:1""",
    ]
  
    try:
      _UpperCAmelCase		:       Any       =    subprocess.Popen(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"""    )
    _UpperCAmelCase		:       Optional[int]       =    ffmpeg_process.communicate(snake_case__    )
    _UpperCAmelCase		:       List[Any]       =    output_stream[0]
  
    _UpperCAmelCase		:       List[Any]       =    np.frombuffer(snake_case__	,      np.floataa    )
    if audio.shape[0] == 0:
      raise ValueError("""Malformed soundfile"""    )
    return audio
  
  
  
  
  
  @add_end_docstrings(A    )
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
  
  
       def __init__(     self       ,				*A_       ,				**A_						):
         # Default, might be overriden by the model.config.
         _UpperCAmelCase		:       Optional[int]       =    5
         super().__init__(*A_       ,				**A_						)
  
         if self.framework != "pt":
           raise ValueError(F'''The {self.__class__} is only available in PyTorch.'''						)
  
         self.check_model_type(A_						)
  
  
       def __call__(     self       ,				A_       ,				**A_       ,				):
         return super().__call__(A_       ,				**A_						)
  
  
       def 					__snake_case(     self       ,				A_=None       ,				**A_						):
         # No parameters on this pipeline right now
         _UpperCAmelCase		:       int       =    {}
         if top_k is not None:
           if top_k > self.model.config.num_labels:
             _UpperCAmelCase		:       Tuple       =    self.model.config.num_labels
           _UpperCAmelCase		:       Dict       =    top_k
         return {}, {}, postprocess_params
  
  
       def 					__snake_case(     self       ,				A_						):
         if isinstance(A_       ,				A_						):
           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		:       str       =    requests.get(A_						).content
           else:
             with open(A_       ,				"""rb"""						) as f:
               _UpperCAmelCase		:       Dict       =    f.read()
  
         if isinstance(A_       ,				A_						):
           _UpperCAmelCase		:       List[Any]       =    ffmpeg_read(A_       ,				self.feature_extractor.sampling_rate						)
  
         if isinstance(A_       ,				A_						):
           # 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		:       Tuple       =    inputs.pop("""raw"""       ,				A_						)
           if _inputs is None:
             # Remove path which will not be used from `datasets`.
             inputs.pop("""path"""       ,				A_						)
             _UpperCAmelCase		:       Dict       =    inputs.pop("""array"""       ,				A_						)
           _UpperCAmelCase		:       Optional[int]       =    inputs.pop("""sampling_rate"""						)
           _UpperCAmelCase		:       Optional[Any]       =    _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		:       List[str]       =    F.resample(
                 torch.from_numpy(A_						)       ,				A_       ,				self.feature_extractor.sampling_rate						).numpy()
  
         if not isinstance(A_       ,				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		:       Any       =    self.feature_extractor(
             A_       ,				sampling_rate=self.feature_extractor.sampling_rate       ,				return_tensors="""pt"""						)
         return processed
  
  
       def 					__snake_case(     self       ,				A_						):
         _UpperCAmelCase		:       Dict       =    self.model(**A_						)
         return model_outputs
  
  
  
  
       def 					__snake_case(     self       ,				A_       ,				A_=5						):
         _UpperCAmelCase		:       List[str]       =    model_outputs.logits[0].softmax(-1						)
         _UpperCAmelCase		:       Dict       =    probs.topk(A_						)
  
         _UpperCAmelCase		:       Union[str, Any]       =    scores.tolist()
         _UpperCAmelCase		:       Dict       =    ids.tolist()
  
         _UpperCAmelCase		:       List[Any]       =    [{"""score""": score, """label""": self.model.config.idalabel[_id]} for score, _id in zip(A_       ,				A_						)]
  
         return labels
  
  
  
  
  
  
style_context: 
  
  
  from dataclasses import dataclass
  from enum import Enum
  from typing import List, Optional, Union
  
  import numpy as np
  import PIL
  from PIL import Image
  
  from ...utils import BaseOutput, is_torch_available, is_transformers_available
  
  
  @dataclass
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
       __SCREAMING_SNAKE_CASE    				=						{
           '''sld_warmup_steps''': 1_5,
           '''sld_guidance_scale''': 2_0,
           '''sld_threshold''': 0.0,
           '''sld_momentum_scale''': 0.0,
           '''sld_mom_beta''': 0.0,
       }
       __SCREAMING_SNAKE_CASE    				=						{
           '''sld_warmup_steps''': 1_0,
           '''sld_guidance_scale''': 1_0_0_0,
           '''sld_threshold''': 0.01,
           '''sld_momentum_scale''': 0.3,
           '''sld_mom_beta''': 0.4,
       }
       __SCREAMING_SNAKE_CASE    				=						{
           '''sld_warmup_steps''': 7,
           '''sld_guidance_scale''': 2_0_0_0,
           '''sld_threshold''': 0.025,
           '''sld_momentum_scale''': 0.5,
           '''sld_mom_beta''': 0.7,
       }
       __SCREAMING_SNAKE_CASE    				=						{
           '''sld_warmup_steps''': 0,
           '''sld_guidance_scale''': 5_0_0_0,
           '''sld_threshold''': 1.0,
           '''sld_momentum_scale''': 0.5,
           '''sld_mom_beta''': 0.7,
       }
  
  
  @dataclass
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
       __SCREAMING_SNAKE_CASE    				=						42
       __SCREAMING_SNAKE_CASE    				=						42
       __SCREAMING_SNAKE_CASE    				=						42
       __SCREAMING_SNAKE_CASE    				=						42
  
  
  if is_transformers_available() and is_torch_available():
   from .pipeline_stable_diffusion_safe import StableDiffusionPipelineSafe
   from .safety_checker import SafeStableDiffusionSafetyChecker
  
  
  
  
  
  