code: 
  """simple docstring"""
  from functools import partial
  from typing import Any, Callable, Dict, List, Type, TypeVar, Union, overload
  
  import torch
  import torch.nn as nn
  import torch.types
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	if not inplace:
  		_UpperCAmelCase =						ma + ma
  	else:
  		ma += ma
  
  	return ma
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						-1 * len(UpperCamelCase__      )
  	_UpperCAmelCase =						list(range(len(tensor.shape[:zero_index]      )      )      )
  	return tensor.permute(first_inds + [zero_index + i for i in inds]      )
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	return t.reshape(t.shape[:-no_dims] + (-1,)      )
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__ = 1E-4      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						mask.expand(*value.shape      )
  	return torch.sum(mask * value				,     dim=UpperCamelCase__      ) / (eps + torch.sum(UpperCamelCase__				,     dim=UpperCamelCase__      ))
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__ = 2.3125				,     UpperCamelCase__ = 21.6875				,     UpperCamelCase__ = 64      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						torch.linspace(UpperCamelCase__				,     UpperCamelCase__				,     no_bins - 1				,     device=pts.device      )
  	_UpperCAmelCase =						torch.sqrt(torch.sum((pts.unsqueeze(-2      ) - pts.unsqueeze(-3      )) ** 2				,     dim=-1      )      )
  	return torch.bucketize(UpperCamelCase__				,     UpperCamelCase__      )
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						dicts[0]
  	_UpperCAmelCase =						{}
  	for k, v in first.items():
  		_UpperCAmelCase =						[d[k] for d in dicts]
  		if isinstance(UpperCamelCase__				,     UpperCamelCase__      ):
  			_UpperCAmelCase =						dict_multimap(UpperCamelCase__				,     UpperCamelCase__      )
  		else:
  			_UpperCAmelCase =						fn(UpperCamelCase__      )
  
  	return new_dict
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						v_bins.view(((1,) * len(x.shape      )) + (len(UpperCamelCase__      ),)      )
  	_UpperCAmelCase =						x[..., None] - reshaped_bins
  	_UpperCAmelCase =						torch.argmin(torch.abs(UpperCamelCase__      )				,     dim=-1      )
  	return nn.functional.one_hot(UpperCamelCase__				,     num_classes=len(UpperCamelCase__      )      ).float()
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__ = 0				,     UpperCamelCase__ = 0      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						[]
  	for i, s in enumerate(data.shape[:no_batch_dims]      ):
  		_UpperCAmelCase =						torch.arange(UpperCamelCase__      )
  		_UpperCAmelCase =						r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape      ) - i - 1)))      )
  		ranges.append(UpperCamelCase__      )
  
  	_UpperCAmelCase =						[slice(UpperCamelCase__      ) for _ in range(len(data.shape      ) - no_batch_dims      )]
  	_UpperCAmelCase =						inds
  	ranges.extend(UpperCamelCase__      )
  	# Matt note: Editing this to get around the behaviour of using a list as an array index changing
  	# in recent Numpy versions
  	return data[tuple(UpperCamelCase__      )]
  
  
  __magic_name__		       =				TypeVar('''T''')
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						{}
  	for k, v in dic.items():
  		if isinstance(UpperCamelCase__				,     UpperCamelCase__      ):
  			_UpperCAmelCase =						dict_map(UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      )
  		else:
  			_UpperCAmelCase =						tree_map(UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      )
  
  	return new_dict
  
  
  
  
  @overload
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	...
  
  
  
  
  @overload
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	...
  
  
  
  
  @overload
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	...
  
  
  
  
  @overload
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	...
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	if isinstance(UpperCamelCase__				,     UpperCamelCase__      ):
  		return dict_map(UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      )
  	elif isinstance(UpperCamelCase__				,     UpperCamelCase__      ):
  		return [tree_map(UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ) for x in tree]
  	elif isinstance(UpperCamelCase__				,     UpperCamelCase__      ):
  		return tuple(tree_map(UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ) for x in tree      )
  	elif isinstance(UpperCamelCase__				,     UpperCamelCase__      ):
  		return fn(UpperCamelCase__      )
  	else:
  		print(type(UpperCamelCase__      )      )
  		raise ValueError("Not supported"      )
  
  
  
  __magic_name__		       =				partial(tree_map, leaf_type=torch.Tensor)
  
  
  
  
  
style_context: 
  """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
  
  __magic_name__		       =				logging.get_logger(__name__)
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""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(UpperCamelCase__				,     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(UpperCamelCase__      )
  	_UpperCAmelCase =						output_stream[0]
  
  	_UpperCAmelCase =						np.frombuffer(UpperCamelCase__				,     np.floataa      )
  	if audio.shape[0] == 0:
  		raise ValueError("Malformed soundfile"      )
  	return audio
  
  
  
  @add_end_docstrings(lowerCamelCase						)
  class    _lowerCAmelCase						(						lowerCamelCase						):
  
  
  
  							def __init__(      self ,						*a_ ,						**a_   )							->							Union[str, Any]:
  								# Default, might be overriden by the model.config.
  								_UpperCAmelCase =						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_ ,						)							->							int:
  								return super().__call__(a_ ,						**a_   )
  
  
  
  							def       _a   (      self ,						a_=None ,						**a_   )							->							Dict:
  								# 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       _a   (      self ,						a_   )							->							str:
  								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 =						requests.get(a_   ).content
  									else:
  										with open(a_ ,						"rb"   ) as f:
  											_UpperCAmelCase =						f.read()
  
  								if isinstance(a_ ,						a_   ):
  									_UpperCAmelCase =						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 =						inputs.pop("raw" ,						a_   )
  									if _inputs is None:
  										# Remove path which will not be used from `datasets`.
  										inputs.pop("path" ,						a_   )
  										_UpperCAmelCase =						inputs.pop("array" ,						a_   )
  									_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(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 =						self.feature_extractor(
  								    a_ ,						sampling_rate=self.feature_extractor.sampling_rate ,						return_tensors="pt"   )
  								return processed
  
  
  
  							def       _a   (      self ,						a_   )							->							List[str]:
  								_UpperCAmelCase =						self.model(**a_   )
  								return model_outputs
  
  
  
  							def       _a   (      self ,						a_ ,						a_=5   )							->							int:
  								_UpperCAmelCase =						model_outputs.logits[0].softmax(-1   )
  								_UpperCAmelCase ,      _UpperCAmelCase =						probs.topk(a_   )
  
  								_UpperCAmelCase =						scores.tolist()
  								_UpperCAmelCase =						ids.tolist()
  
  								_UpperCAmelCase =						[{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(a_ ,						a_   )]
  
  								return labels
  
  
  
  
  