




import inspect
import warnings

import torch

from .state import AcceleratorState, GradientState
from .utils import DistributedType, honor_type, is_tpu_available


if is_tpu_available(check_device=False):
       import torch_xla.core.xla_model as xm

def   A   (   _SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE					)			->				List[Any]:
       if isinstance(_SCREAMING_SNAKE_CASE				,(list, tuple)					):
              return honor_type(_SCREAMING_SNAKE_CASE				,(move_to_device(_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE					) for t in state)					)
       elif isinstance(_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE					):
              return type(_SCREAMING_SNAKE_CASE					)({k: move_to_device(_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE					) for k, v in state.items()}					)
       elif isinstance(_SCREAMING_SNAKE_CASE				,torch.Tensor					):
              return state.to(_SCREAMING_SNAKE_CASE					)
       return state




class 	UpperCamelCase__			(torch.optim.Optimizer  ):

    '''simple docstring'''



    def __init__(					self  ,						UpperCamelCase__  ,						UpperCamelCase__=True  ,						UpperCamelCase__=None  )  ->   Tuple:
           lowerCamelCase     :   Union[str, Any]    				=      optimizer
           lowerCamelCase     :   Tuple    				=      scaler
           lowerCamelCase     :   str    				=      AcceleratorState()
           lowerCamelCase     :   Union[str, Any]    				=      GradientState()
           lowerCamelCase     :   Dict    				=      device_placement
           lowerCamelCase     :   List[Any]    				=      False
           lowerCamelCase     :   str    				=      None

           # Handle device placement
           if device_placement:
                  lowerCamelCase     :   Dict    				=      self.optimizer.state_dict()
                  if self.accelerator_state.distributed_type == DistributedType.TPU:
                         xm.send_cpu_data_to_device(UpperCamelCase__  ,						self.accelerator_state.device  )
                  else:
                         lowerCamelCase     :   Tuple    				=      move_to_device(UpperCamelCase__  ,						self.accelerator_state.device  )
                  self.optimizer.load_state_dict(UpperCamelCase__  )







    @property
    def 					_lowercase  (					self  )  ->   int:
           return self.optimizer.state







    @state.setter
    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   Tuple:
           lowerCamelCase     :   str    				=      state







    @property
    def 					_lowercase  (					self  )  ->   Union[str, Any]:
           return self.optimizer.param_groups







    @param_groups.setter
    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   Dict:
           lowerCamelCase     :   int    				=      param_groups







    @property
    def 					_lowercase  (					self  )  ->   str:
           return self.optimizer.defaults







    @defaults.setter
    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   Tuple:
           lowerCamelCase     :   Optional[Any]    				=      defaults







    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   Any:
           self.optimizer.add_param_group(UpperCamelCase__  )







    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   Tuple:
           if self.accelerator_state.distributed_type == DistributedType.TPU and self.device_placement:
                  xm.send_cpu_data_to_device(UpperCamelCase__  ,						self.accelerator_state.device  )
           self.optimizer.load_state_dict(UpperCamelCase__  )







    def 					_lowercase  (					self  )  ->   str:
           return self.optimizer.state_dict()







    def 					_lowercase  (					self  ,						UpperCamelCase__=None  )  ->   List[str]:
           if self.gradient_state.sync_gradients:
                  lowerCamelCase     :   str    				=      "set_to_none" in inspect.signature(self.optimizer.zero_grad  ).parameters
                  if accept_arg:
                         if set_to_none is None:
                                lowerCamelCase     :   str    				=      False
                         self.optimizer.zero_grad(set_to_none=UpperCamelCase__  )
                  else:
                         if set_to_none is not None:
                                raise ValueError("`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer."  )
                         self.optimizer.zero_grad()







    def 					_lowercase  (					self  ,						UpperCamelCase__=None  )  ->   Optional[Any]:
           if self.gradient_state.sync_gradients:
                  if self.accelerator_state.distributed_type == DistributedType.TPU:
                         lowerCamelCase     :   Tuple    				=      {"closure": closure} if closure is not None else {}
                         xm.optimizer_step(self.optimizer  ,						optimizer_args=UpperCamelCase__  )
                  elif self.scaler is not None:
                         lowerCamelCase     :   Optional[int]    				=      False
                         if self._last_scale is None:
                                # `get_scale` is an async operation requiring full synchronization
                                # on CPU and GPUs before finishing. As a result, we store away
                                # the prior one to reduce the call overhead
                                lowerCamelCase     :   Tuple    				=      self.scaler.get_scale()
                                lowerCamelCase     :   Union[str, Any]    				=      True
                         self.scaler.step(self.optimizer  ,						UpperCamelCase__  )
                         self.scaler.update()
                         lowerCamelCase     :   Dict    				=      self.scaler.get_scale()
                         if not new_scale:
                                # If we reduced the loss scale, it means the optimizer step was skipped because of gradient overflow.
                                lowerCamelCase     :   Any    				=      scale_after < self._last_scale
                         lowerCamelCase     :   Optional[Any]    				=      scale_after

                  else:
                         self.optimizer.step(UpperCamelCase__  )







    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   List[Any]:
           for param_group in self.optimizer.param_groups:
                  lowerCamelCase     :   int    				=      [parameters_map.get(UpperCamelCase__  ,						UpperCamelCase__  ) for p in param_group["params"]]







    @property
    def 					_lowercase  (					self  )  ->   Dict:
           warnings.warn(
               "The `is_overflow` property is deprecated and will be removed in version 1.0 of Accelerate use "
               "`optimizer.step_was_skipped` instead."  ,						UpperCamelCase__  ,						)
           return self._is_overflow







    @property
    def 					_lowercase  (					self  )  ->   Tuple:
           return self._is_overflow







    def __getstate__(					self  )  ->   str:
           return self.__dict__.copy()







    def __setstate__(					self  ,						UpperCamelCase__  )  ->   Tuple:
           self.__dict__.update(UpperCamelCase__  )












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__ :   Union[str, Any]						=     logging.get_logger(__name__)

def   A   (   _SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE					)			->				np.array:
       lowerCamelCase     :   Optional[Any]    				=      f'''{sampling_rate}'''
       lowerCamelCase     :   Optional[Any]    				=      "1"
       lowerCamelCase     :   Tuple    				=      "f32le"
       lowerCamelCase     :   Any    				=      [
           "ffmpeg",
           "-i",
           "pipe:0",
           "-ac",
           ac,
           "-ar",
           ar,
           "-f",
           format_for_conversion,
           "-hide_banner",
           "-loglevel",
           "quiet",
           "pipe:1",
       ]

       try:
              lowerCamelCase     :   Optional[int]    				=      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"					)
       lowerCamelCase     :   Optional[int]    				=      ffmpeg_process.communicate(_SCREAMING_SNAKE_CASE					)
       lowerCamelCase     :   Union[str, Any]    				=      output_stream[0]

       lowerCamelCase     :   Dict    				=      np.frombuffer(_SCREAMING_SNAKE_CASE				,np.floataa					)
       if audio.shape[0] == 0:
              raise ValueError("Malformed soundfile"					)
       return audio




@add_end_docstrings(lowerCAmelCase__  )
class 	UpperCamelCase__			(lowerCAmelCase__  ):

    '''simple docstring'''



    def __init__(					self  ,						*UpperCamelCase__  ,						**UpperCamelCase__  )  ->   Dict:
           # Default, might be overriden by the model.config.
           lowerCamelCase     :   Union[str, Any]    				=      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__  ,						)  ->   Optional[int]:
           return super().__call__(UpperCamelCase__  ,						**UpperCamelCase__  )







    def 					_lowercase  (					self  ,						UpperCamelCase__=None  ,						**UpperCamelCase__  )  ->   str:
           # No parameters on this pipeline right now
           lowerCamelCase     :   int    				=      {}
           if top_k is not None:
                  if top_k > self.model.config.num_labels:
                         lowerCamelCase     :   Any    				=      self.model.config.num_labels
                  lowerCamelCase     :   Any    				=      top_k
           return {}, {}, postprocess_params







    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   Dict:
           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
                         lowerCamelCase     :   str    				=      requests.get(UpperCamelCase__  ).content
                  else:
                         with open(UpperCamelCase__  ,						"rb"  ) as f:
                                lowerCamelCase     :   int    				=      f.read()

           if isinstance(UpperCamelCase__  ,						UpperCamelCase__  ):
                  lowerCamelCase     :   str    				=      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"  )

                  lowerCamelCase     :   Optional[int]    				=      inputs.pop("raw"  ,						UpperCamelCase__  )
                  if _inputs is None:
                         # Remove path which will not be used from `datasets`.
                         inputs.pop("path"  ,						UpperCamelCase__  )
                         lowerCamelCase     :   List[str]    				=      inputs.pop("array"  ,						UpperCamelCase__  )
                  lowerCamelCase     :   str    				=      inputs.pop("sampling_rate"  )
                  lowerCamelCase     :   Union[str, 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`."  )

                         lowerCamelCase     :   Tuple    				=      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"  )

           lowerCamelCase     :   Optional[int]    				=      self.feature_extractor(
               UpperCamelCase__  ,						sampling_rate=self.feature_extractor.sampling_rate  ,						return_tensors="pt"  )
           return processed







    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   str:
           lowerCamelCase     :   Optional[Any]    				=      self.model(**UpperCamelCase__  )
           return model_outputs







    def 					_lowercase  (					self  ,						UpperCamelCase__  ,						UpperCamelCase__=5  )  ->   Tuple:
           lowerCamelCase     :   Tuple    				=      model_outputs.logits[0].softmax(-1  )
           lowerCamelCase				,   lowerCamelCase     :   str    				=      probs.topk(UpperCamelCase__  )

           lowerCamelCase     :   str    				=      scores.tolist()
           lowerCamelCase     :   Optional[int]    				=      ids.tolist()

           lowerCamelCase     :   Optional[int]    				=      [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCamelCase__  ,						UpperCamelCase__  )]

           return labels






