





from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available







def    UpperCAmelCase				(  _lowerCamelCase   :	Optional[Any]  ):





						'''simple docstring'''


						if is_torch_available():
												import torch

												if isinstance(_lowerCAmelCase      , torch.Tensor  ):
																		return True

						return isinstance(_lowerCAmelCase      , np.ndarray  )



class  _a  (					lowercase__				):






							"""simple docstring"""

							def   A_	(   self					:  str     )						->Union[str, Any]:
													SCREAMING_SNAKE_CASE__  :					str =       fields(self     )

													# Safety and consistency checks
													if not len(a     ):
																			raise ValueError(f"""{self.__class__.__name__} has no fields."""     )

													SCREAMING_SNAKE_CASE__  :					List[str] =       getattr(self				,						class_fields[0].name     )
													SCREAMING_SNAKE_CASE__  :					Optional[int] =       all(getattr(self				,						field.name     ) is None for field in class_fields[1:]     )

													if other_fields_are_none and isinstance(a				,						a     ):
																			for key, value in first_field.items():
																									SCREAMING_SNAKE_CASE__  :					str =       value
													else:
																			for field in class_fields:
																									SCREAMING_SNAKE_CASE__  :					Tuple =       getattr(self				,						field.name     )
																									if v is not None:
																															SCREAMING_SNAKE_CASE__  :					Optional[int] =       v

							def __delitem__(   self					:  List[str]				,						*a					:  str				,						**a					:  Optional[Any]     )						->int:
													raise Exception(f"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""     )

							def   A_	(   self					:  str				,						*a					:  str				,						**a					:  Union[str, Any]     )						->int:
													raise Exception(f"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""     )

							def   A_	(   self					:  Any				,						*a					:  Optional[Any]				,						**a					:  Optional[Any]     )						->int:
													raise Exception(f"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""     )

							def   A_	(   self					:  Optional[Any]				,						*a					:  Optional[int]				,						**a					:  Optional[int]     )						->str:
													raise Exception(f"""You cannot use ``update`` on a {self.__class__.__name__} instance."""     )

							def __getitem__(   self					:  int				,						a					:  Tuple     )						->Tuple:
													if isinstance(a				,						a     ):
																			SCREAMING_SNAKE_CASE__  :					Any =       dict(self.items()     )
																			return inner_dict[k]
													else:
																			return self.to_tuple()[k]

							def __setattr__(   self					:  Optional[Any]				,						a					:  Optional[int]				,						a					:  List[Any]     )						->Optional[Any]:
													if name in self.keys() and value is not None:
																			# Don't call self.__setitem__ to avoid recursion errors
																			super().__setitem__(a				,						a     )
													super().__setattr__(a				,						a     )

							def __setitem__(   self					:  int				,						a					:  List[Any]				,						a					:  Any     )						->List[str]:
													# Will raise a KeyException if needed
													super().__setitem__(a				,						a     )
													# Don't call self.__setattr__ to avoid recursion errors
													super().__setattr__(a				,						a     )






							def   A_	(   self					:  Union[str, Any]     )						->Tuple[Any]:
													return tuple(self[k] for k in self.keys()     )





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    : List[str]		= logging.get_logger(__name__)



def     lowerCAmelCase		(		_lowerCAmelCase				: bytes    ,				_lowerCAmelCase				: int						):




 """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(_lowerCAmelCase    ,				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(_lowerCAmelCase						)
 UpperCAmelCase__							=    output_stream[0]

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


@add_end_docstrings(lowerCAmelCase		)
class       _UpperCamelCase   (					lowerCAmelCase		):
      def __init__(      self :Any			,   *lowerCamelCase :Any			,   **lowerCamelCase :Optional[Any]   )  ->      Optional[int]:
       # Default, might be overriden by the model.config.
       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 :Optional[Any]			,   lowerCamelCase :Union[np.ndarray, bytes, str]			,   **lowerCamelCase :List[Any]			,   )  ->      Tuple:
       return super().__call__(lowerCamelCase			,   **lowerCamelCase   )
      def 						UpperCAmelCase_    (      self :str			,   lowerCamelCase :Dict=None			,   **lowerCamelCase :str   )  ->      int:
       # No parameters on this pipeline right now
       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 						UpperCAmelCase_    (      self :Optional[Any]			,   lowerCamelCase :Dict   )  ->      Optional[int]:
       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 						UpperCAmelCase_    (      self :Tuple			,   lowerCamelCase :Union[str, Any]   )  ->      List[Any]:
       UpperCAmelCase__							=    self.model(**lowerCamelCase   )
       return model_outputs







      def 						UpperCAmelCase_    (      self :List[str]			,   lowerCamelCase :Optional[Any]			,   lowerCamelCase :List[Any]=5   )  ->      Tuple:
       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





