

from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


lowerCamelCase   					=  logging.get_logger(__name__)

lowerCamelCase   					=  {
    '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/config.json''',
    # See all M2M100 models at https://huggingface.co/models?filter=m2m_100
}





class      snake_case_      (					_a				):


							"""simple docstring"""





							__UpperCAmelCase      ="""m2m_100"""
							__UpperCAmelCase      =["""past_key_values"""]
							__UpperCAmelCase      ={"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}




							def __init__(			self       ,    _A=1_2_8_1_1_2       ,    _A=1_0_2_4       ,    _A=1_2       ,    _A=4_0_9_6       ,    _A=1_6       ,    _A=1_2       ,    _A=4_0_9_6       ,    _A=1_6       ,    _A=0.05       ,    _A=0.05       ,    _A=True       ,    _A=True       ,    _A="relu"       ,    _A=1_0_2_4       ,    _A=0.1       ,    _A=0.1       ,    _A=0.0       ,    _A=0.02       ,    _A=2       ,    _A=True       ,    _A=1       ,    _A=0       ,    _A=2       ,    **_A       ,    ):
												__lowerCAmelCase       =				vocab_size
												__lowerCAmelCase       =				max_position_embeddings
												__lowerCAmelCase       =				d_model
												__lowerCAmelCase       =				encoder_ffn_dim
												__lowerCAmelCase       =				encoder_layers
												__lowerCAmelCase       =				encoder_attention_heads
												__lowerCAmelCase       =				decoder_ffn_dim
												__lowerCAmelCase       =				decoder_layers
												__lowerCAmelCase       =				decoder_attention_heads
												__lowerCAmelCase       =				dropout
												__lowerCAmelCase       =				attention_dropout
												__lowerCAmelCase       =				activation_dropout
												__lowerCAmelCase       =				activation_function
												__lowerCAmelCase       =				init_std
												__lowerCAmelCase       =				encoder_layerdrop
												__lowerCAmelCase       =				decoder_layerdrop
												__lowerCAmelCase       =				use_cache
												__lowerCAmelCase       =				encoder_layers
												__lowerCAmelCase       =				scale_embedding  # scale factor will be sqrt(d_model) if True

												super().__init__(
												    pad_token_id=_A       ,    bos_token_id=_A       ,    eos_token_id=_A       ,    is_encoder_decoder=_A       ,    decoder_start_token_id=_A       ,    **_A       ,    )





class      snake_case_      (					_a				):


							"""simple docstring"""





							@property
							def 							A__	(			self				):
												__lowerCAmelCase       =				OrderedDict(
												    [
												        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
												        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
												    ]				)

												if self.use_past:
																	__lowerCAmelCase       =				{0: 'batch'}
																	__lowerCAmelCase       =				{0: 'batch', 1: 'past_decoder_sequence + sequence'}
												else:
																	__lowerCAmelCase       =				{0: 'batch', 1: 'decoder_sequence'}
																	__lowerCAmelCase       =				{0: 'batch', 1: 'decoder_sequence'}

												if self.use_past:
																	self.fill_with_past_key_values_(_A       ,    direction='inputs'				)
												return common_inputs




							def 							A__	(			self       ,    _A       ,    _A = -1       ,    _A = -1       ,    _A = False       ,    _A = None       ,    ):
												# Copied from OnnxConfig.generate_dummy_inputs
												# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
												# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
												__lowerCAmelCase       =				compute_effective_axis_dimension(
												    _A       ,    fixed_dimension=OnnxConfig.default_fixed_batch       ,    num_token_to_add=0				)

												# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
												__lowerCAmelCase       =				tokenizer.num_special_tokens_to_add(_A				)
												__lowerCAmelCase       =				compute_effective_axis_dimension(
												    _A       ,    fixed_dimension=OnnxConfig.default_fixed_sequence       ,    num_token_to_add=_A				)

												# Generate dummy inputs according to compute batch and sequence
												__lowerCAmelCase       =				[' '.join([tokenizer.unk_token]				) * seq_length] * batch_size
												__lowerCAmelCase       =				dict(tokenizer(_A       ,    return_tensors=_A				)				)
												return common_inputs




							def 							A__	(			self       ,    _A       ,    _A = -1       ,    _A = -1       ,    _A = False       ,    _A = None       ,    ):
												__lowerCAmelCase       =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
												    _A       ,    _A       ,    _A       ,    _A       ,    _A				)

												# Generate decoder inputs
												__lowerCAmelCase       =				seq_length if not self.use_past else 1
												__lowerCAmelCase       =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
												    _A       ,    _A       ,    _A       ,    _A       ,    _A				)
												__lowerCAmelCase       =				{F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
												__lowerCAmelCase       =				dict(**_A       ,    **_A				)

												if self.use_past:
																	if not is_torch_available():
																						raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'				)
																	else:
																						import torch
																	__lowerCAmelCase,						__lowerCAmelCase       =				common_inputs['input_ids'].shape
																	__lowerCAmelCase       =				common_inputs['decoder_input_ids'].shape[1]
																	__lowerCAmelCase,						__lowerCAmelCase       =				self.num_attention_heads
																	__lowerCAmelCase       =				(
																	    batch,
																	    num_encoder_attention_heads,
																	    encoder_seq_length,
																	    self._config.hidden_size // num_encoder_attention_heads,
																	)
																	__lowerCAmelCase       =				decoder_seq_length + 3
																	__lowerCAmelCase       =				(
																	    batch,
																	    num_decoder_attention_heads,
																	    decoder_past_length,
																	    self._config.hidden_size // num_decoder_attention_heads,
																	)

																	__lowerCAmelCase       =				torch.cat(
																	    [common_inputs['decoder_attention_mask'], torch.ones(_A       ,    _A				)]       ,    dim=1				)

																	__lowerCAmelCase       =				[]
																	# If the number of encoder and decoder layers are present in the model configuration, both are considered
																	__lowerCAmelCase,						__lowerCAmelCase       =				self.num_layers
																	__lowerCAmelCase       =				min(_A       ,    _A				)
																	__lowerCAmelCase       =				max(_A       ,    _A				) - min_num_layers
																	__lowerCAmelCase       =				'encoder' if num_encoder_layers > num_decoder_layers else 'decoder'

																	for _ in range(_A				):
																						common_inputs["past_key_values"].append(
																						    (
																						        torch.zeros(_A				),
																						        torch.zeros(_A				),
																						        torch.zeros(_A				),
																						        torch.zeros(_A				),
																						    )				)
																	# TODO: test this.
																	__lowerCAmelCase       =				encoder_shape if remaining_side_name == 'encoder' else decoder_shape
																	for _ in range(_A       ,    _A				):
																						common_inputs["past_key_values"].append((torch.zeros(_A				), torch.zeros(_A				))				)
												return common_inputs


							__UpperCAmelCase      =_generate_dummy_inputs_for_default_and_seqaseq_lm









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






