



'''simple docstring'''







import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
							import torch


SCREAMING_SNAKE_CASE__     : Optional[int]				=   logging.get_logger(__name__)




class 				__lowerCAmelCase:






			def __init__(   self  :							List[str]      ,       SCREAMING_SNAKE_CASE  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							Union[str, Any]=21      ,       SCREAMING_SNAKE_CASE  :							str=[]      ,       SCREAMING_SNAKE_CASE  :							Dict=None	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Optional[int]										=      model
					SCREAMING_SNAKE_CASE_						:List[Any]										=      trace_batch_nums
					SCREAMING_SNAKE_CASE_						:str										=      abort_after_batch_num

					# keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
					SCREAMING_SNAKE_CASE_						:Any										=      collections.deque([]      ,       SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:List[str]										=      []
					SCREAMING_SNAKE_CASE_						:Optional[int]										=      0
					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      0
					SCREAMING_SNAKE_CASE_						:List[Any]										=      False
					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      '                 '

					self.analyse_model()

					self.register_forward_hook()






			def 				_lowercase	(   self  :							Tuple      ,       SCREAMING_SNAKE_CASE  :							Any=None	):




					"""simple docstring"""







					if frame is not None:
							self.expand_frame(SCREAMING_SNAKE_CASE	)
					self.frames.append('\n'.join(self.frame	)	)
					SCREAMING_SNAKE_CASE_						:List[str]										=      []  # start a new frame






			def 				_lowercase	(   self  :							Dict      ,       SCREAMING_SNAKE_CASE  :							Tuple	):




					"""simple docstring"""







					self.frame.append(SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							List[Any]	):




					"""simple docstring"""







					print('\n'.join(self.frames	)	)
					SCREAMING_SNAKE_CASE_						:Optional[int]										=      []






			def 				_lowercase	(   self  :							Dict	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Tuple										=      []






			def 				_lowercase	(   self  :							Tuple	):




					"""simple docstring"""







					print(f'\nDetected inf/nan during batch_number={self.batch_number}'	)
					print(f'Last {len(self.frames	)} forward frames:'	)
					print(f'{"abs min":8} {"abs max":8} metadata'	)
					print('\n'.join(self.frames	)	)
					print('\n\n'	)
					SCREAMING_SNAKE_CASE_						:Tuple										=      []






			def 				_lowercase	(   self  :							Dict	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Tuple										=      {m: name for name, m in self.model.named_modules()}
					# self.longest_module_name = max(len(v) for v in self.module_names.values())






			def 				_lowercase	(   self  :							Union[str, Any]      ,       SCREAMING_SNAKE_CASE  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							Optional[int]	):




					"""simple docstring"""







					if torch.is_tensor(SCREAMING_SNAKE_CASE	):
							self.expand_frame(get_abs_min_max(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)	)
							if detect_overflow(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	):
									SCREAMING_SNAKE_CASE_						:Optional[int]										=      True
					elif var is None:
							self.expand_frame(f'{"None":>17} {ctx}'	)
					else:
							self.expand_frame(f'{"not a tensor":>17} {ctx}'	)






			def 				_lowercase	(   self  :							Tuple	):




					"""simple docstring"""







					self.expand_frame(f'\n\n{self.prefix} *** Starting batch number={self.batch_number} ***'	)
					self.expand_frame(f'{"abs min":8} {"abs max":8} metadata'	)






			def 				_lowercase	(   self  :							int	):




					"""simple docstring"""







					self.expand_frame(f'{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'	)






			def 				_lowercase	(   self  :							Tuple      ,       SCREAMING_SNAKE_CASE  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							List[str]	):




					"""simple docstring"""







					self.expand_frame(f'{self.prefix} {self.module_names[module]} {module.__class__.__name__}'	)

					# params
					for name, p in module.named_parameters(recurse=SCREAMING_SNAKE_CASE	):
							self.analyse_variable(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)

					# inputs
					if isinstance(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	):
							for i, x in enumerate(SCREAMING_SNAKE_CASE	):
									self.analyse_variable(SCREAMING_SNAKE_CASE      ,       f'input[{i}]'	)
					else:
							self.analyse_variable(SCREAMING_SNAKE_CASE      ,       'input'	)

					# outputs
					if isinstance(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	):
							for i, x in enumerate(SCREAMING_SNAKE_CASE	):
									# possibly a tuple of tuples
									if isinstance(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	):
											for j, y in enumerate(SCREAMING_SNAKE_CASE	):
													self.analyse_variable(SCREAMING_SNAKE_CASE      ,       f'output[{i}][{j}]'	)
									else:
											self.analyse_variable(SCREAMING_SNAKE_CASE      ,       f'output[{i}]'	)
					else:
							self.analyse_variable(SCREAMING_SNAKE_CASE      ,       'output'	)

					self.save_frame()






			def 				_lowercase	(   self  :							Union[str, Any]	):




					"""simple docstring"""







					self.model.apply(self._register_forward_hook	)






			def 				_lowercase	(   self  :							Optional[int]      ,       SCREAMING_SNAKE_CASE  :							List[Any]	):




					"""simple docstring"""







					module.register_forward_hook(self.forward_hook	)






			def 				_lowercase	(   self  :							str      ,       SCREAMING_SNAKE_CASE  :							Any      ,       SCREAMING_SNAKE_CASE  :							List[str]      ,       SCREAMING_SNAKE_CASE  :							Optional[int]	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:List[Any]										=      False

					SCREAMING_SNAKE_CASE_						:Tuple										=      True if self.batch_number in self.trace_batch_nums else False
					if trace_mode:
							self.reset_saved_frames()

					if self.total_calls == 0:
							self.batch_start_frame()
					self.total_calls += 1

					# count batch numbers - the very first forward hook of the batch will be called when the
					# batch completes - i.e. it gets called very last - we know this batch has finished
					if module == self.model:
							self.batch_number += 1
							SCREAMING_SNAKE_CASE_						:List[str]										=      True

					self.create_frame(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)

					# if last_frame_of_batch:
					#     self.batch_end_frame()

					if trace_mode:
							self.trace_frames()

					if last_frame_of_batch:
							self.batch_start_frame()

					if self.detected_overflow and not trace_mode:
							self.dump_saved_frames()

							# now we can abort, as it's pointless to continue running
							raise ValueError(
							    'DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. '
							    'Please scroll up above this traceback to see the activation values prior to this event.'	)

					# abort after certain batch if requested to do so
					if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
							raise ValueError(
							    f'DebugUnderflowOverflow: aborting after {self.batch_number} batches due to'
							    f' `abort_after_batch_num={self.abort_after_batch_num}` arg'	)







def  SCREAMING_SNAKE_CASE__ (				SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE     ):
		SCREAMING_SNAKE_CASE_						:Optional[int]										=      var.abs()
		return F'{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'







def  SCREAMING_SNAKE_CASE__ (				SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE     ):
		SCREAMING_SNAKE_CASE_						:Any										=      False
		if torch.isnan(SCREAMING_SNAKE_CASE     ).any().item():
				SCREAMING_SNAKE_CASE_						:Tuple										=      True
				print(F'{ctx} has nans'     )
		if torch.isinf(SCREAMING_SNAKE_CASE     ).any().item():
				SCREAMING_SNAKE_CASE_						:List[str]										=      True
				print(F'{ctx} has infs'     )

		# if needed to monitor large elements can enable the following
		if 0:  # and detected:
				SCREAMING_SNAKE_CASE_						:Dict										=      var[torch.ge(var.abs() ,		100     )]
				if naaa.numel() > 0:
						print(F'{ctx}:  n100={naaa.numel()}'     )
				SCREAMING_SNAKE_CASE_						:Dict										=      var[torch.ge(var.abs() ,		1000     )]
				if naaaa.numel() > 0:
						print(F'{ctx}: n1000={naaaa.numel()}'     )
				SCREAMING_SNAKE_CASE_						:Tuple										=      var[torch.ge(var.abs() ,		1_0000     )]
				if naaaaa.numel() > 0:
						print(F'{ctx}: n10000={naaaaa.numel()}'     )

		if 0:
				print(F'min={var.min():9.2e} max={var.max():9.2e}'     )

		if 0:
				print(F'min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})'     )

		return detected





class 				__lowerCAmelCase(							lowerCAmelCase__      ):
			__snake_case  :		List[Any]		=      'underflow_overflow'
			__snake_case  :		Optional[int]		=      'tpu_metrics_debug'



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   					=  logging.get_logger(__name__)


def 							__lowercase     (	UpperCAmelCase__		,       UpperCAmelCase__   ):

					"""simple docstring"""






					__lowerCAmelCase       =				F"""{sampling_rate}"""
					__lowerCAmelCase       =				'1'
					__lowerCAmelCase       =				'f32le'
					__lowerCAmelCase       =				[
					    'ffmpeg',
					    '-i',
					    'pipe:0',
					    '-ac',
					    ac,
					    '-ar',
					    ar,
					    '-f',
					    format_for_conversion,
					    '-hide_banner',
					    '-loglevel',
					    'quiet',
					    'pipe:1',
					]

					try:
										__lowerCAmelCase       =				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'   )
					__lowerCAmelCase       =				ffmpeg_process.communicate(UpperCAmelCase__   )
					__lowerCAmelCase       =				output_stream[0]

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





@add_end_docstrings(_a				)
class      snake_case_      (					_a				):


							"""simple docstring"""





							def __init__(			self       ,    *_A       ,    **_A				):
												# Default, might be overriden by the model.config.
												__lowerCAmelCase       =				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 							A__	(			self       ,    _A=None       ,    **_A				):
												# No parameters on this pipeline right now
												__lowerCAmelCase       =				{}
												if top_k is not None:
																	if top_k > self.model.config.num_labels:
																						__lowerCAmelCase       =				self.model.config.num_labels
																	__lowerCAmelCase       =				top_k
												return {}, {}, postprocess_params




							def 							A__	(			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
																						__lowerCAmelCase       =				requests.get(_A				).content
																	else:
																						with open(_A       ,    'rb'				) as f:
																											__lowerCAmelCase       =				f.read()

												if isinstance(_A       ,    _A				):
																	__lowerCAmelCase       =				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'				)

																	__lowerCAmelCase       =				inputs.pop('raw'       ,    _A				)
																	if _inputs is None:
																						# Remove path which will not be used from `datasets`.
																						inputs.pop('path'       ,    _A				)
																						__lowerCAmelCase       =				inputs.pop('array'       ,    _A				)
																	__lowerCAmelCase       =				inputs.pop('sampling_rate'				)
																	__lowerCAmelCase       =				_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       =				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'				)

												__lowerCAmelCase       =				self.feature_extractor(
												    _A       ,    sampling_rate=self.feature_extractor.sampling_rate       ,    return_tensors='pt'				)
												return processed




							def 							A__	(			self       ,    _A				):
												__lowerCAmelCase       =				self.model(**_A				)
												return model_outputs




							def 							A__	(			self       ,    _A       ,    _A=5				):
												__lowerCAmelCase       =				model_outputs.logits[0].softmax(-1				)
												__lowerCAmelCase,						__lowerCAmelCase       =				probs.topk(_A				)

												__lowerCAmelCase       =				scores.tolist()
												__lowerCAmelCase       =				ids.tolist()

												__lowerCAmelCase       =				[{'score': score, 'label': self.model.config.idalabel[_id]} for score, _id in zip(_A       ,    _A				)]

												return labels






