



import collections
import inspect
import unittest

from transformers import SwinConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel
		from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor


class 	lowerCamelCase__ :


						def __init__( self						:  Any      ,       _a						:  List[Any]      ,       _a						:  List[Any]=1_3      ,       _a						:  Optional[int]=3_2      ,       _a						:  str=2      ,       _a						:  List[Any]=3      ,       _a						:  str=1_6      ,       _a						:  Tuple=[1, 2, 1]      ,       _a						:  Union[str, Any]=[2, 2, 4]      ,       _a						:  List[str]=2      ,       _a						:  int=2.0      ,       _a						:  Union[str, Any]=True      ,       _a						:  Optional[Any]=0.0      ,       _a						:  List[str]=0.0      ,       _a						:  Union[str, Any]=0.1      ,       _a						:  Dict="gelu"      ,       _a						:  Optional[Any]=False      ,       _a						:  List[str]=True      ,       _a						:  Any=0.0_2      ,       _a						:  Union[str, Any]=1e-5      ,       _a						:  int=True      ,       _a						:  Optional[Any]=None      ,       _a						:  str=True      ,       _a						:  List[Any]=1_0      ,       _a						:  str=8      ,       _a						:  Optional[Any]=["stage1", "stage2"]      ,       _a						:  Any=[1, 2]      ,       ):
													a__:       Tuple											=parent
													a__:       Optional[int]											=batch_size
													a__:       Any											=image_size
													a__:       List[str]											=patch_size
													a__:       Union[str, Any]											=num_channels
													a__:       str											=embed_dim
													a__:       Optional[int]											=depths
													a__:       List[Any]											=num_heads
													a__:       Optional[Any]											=window_size
													a__:       Optional[Any]											=mlp_ratio
													a__:       Optional[int]											=qkv_bias
													a__:       Any											=hidden_dropout_prob
													a__:       Dict											=attention_probs_dropout_prob
													a__:       Any											=drop_path_rate
													a__:       Tuple											=hidden_act
													a__:       Optional[Any]											=use_absolute_embeddings
													a__:       List[Any]											=patch_norm
													a__:       Tuple											=layer_norm_eps
													a__:       str											=initializer_range
													a__:       List[str]											=is_training
													a__:       str											=scope
													a__:       Union[str, Any]											=use_labels
													a__:       int											=type_sequence_label_size
													a__:       int											=encoder_stride
													a__:       List[Any]											=out_features
													a__:       Optional[Any]											=out_indices


						def   _lowerCamelCase			( self						:  str			):
													a__:       Union[str, Any]											=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

													a__:       Optional[Any]											=None
													if self.use_labels:
																				a__:       int											=ids_tensor([self.batch_size]      ,       self.type_sequence_label_size			)

													a__:       Any											=self.get_config()

													return config, pixel_values, labels


						def   _lowerCamelCase			( self						:  Any			):
													return SwinConfig(
													    image_size=self.image_size      ,       patch_size=self.patch_size      ,       num_channels=self.num_channels      ,       embed_dim=self.embed_dim      ,       depths=self.depths      ,       num_heads=self.num_heads      ,       window_size=self.window_size      ,       mlp_ratio=self.mlp_ratio      ,       qkv_bias=self.qkv_bias      ,       hidden_dropout_prob=self.hidden_dropout_prob      ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,       drop_path_rate=self.drop_path_rate      ,       hidden_act=self.hidden_act      ,       use_absolute_embeddings=self.use_absolute_embeddings      ,       path_norm=self.patch_norm      ,       layer_norm_eps=self.layer_norm_eps      ,       initializer_range=self.initializer_range      ,       encoder_stride=self.encoder_stride      ,       out_features=self.out_features      ,       out_indices=self.out_indices      ,       )


						def   _lowerCamelCase			( self						:  str      ,       _a						:  Any      ,       _a						:  str      ,       _a						:  Any			):
													a__:       Any											=SwinModel(config=_a			)
													model.to(_a			)
													model.eval()
													a__:       Optional[Any]											=model(_a			)

													a__:       Tuple											=((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
													a__:       List[str]											=int(config.embed_dim * 2 ** (len(config.depths			) - 1)			)

													self.parent.assertEqual(result.last_hidden_state.shape      ,       (self.batch_size, expected_seq_len, expected_dim)			)


						def   _lowerCamelCase			( self						:  List[Any]      ,       _a						:  Optional[int]      ,       _a						:  List[Any]      ,       _a						:  Dict			):
													a__:       Tuple											=SwinBackbone(config=_a			)
													model.to(_a			)
													model.eval()
													a__:       List[Any]											=model(_a			)

													# verify hidden states
													self.parent.assertEqual(len(result.feature_maps			)      ,       len(config.out_features			)			)
													self.parent.assertListEqual(list(result.feature_maps[0].shape			)      ,       [self.batch_size, model.channels[0], 1_6, 1_6]			)

													# verify channels
													self.parent.assertEqual(len(model.channels			)      ,       len(config.out_features			)			)

													# verify backbone works with out_features=None
													a__:       int											=None
													a__:       str											=SwinBackbone(config=_a			)
													model.to(_a			)
													model.eval()
													a__:       Dict											=model(_a			)

													# verify feature maps
													self.parent.assertEqual(len(result.feature_maps			)      ,       1			)
													self.parent.assertListEqual(list(result.feature_maps[0].shape			)      ,       [self.batch_size, model.channels[-1], 4, 4]			)

													# verify channels
													self.parent.assertEqual(len(model.channels			)      ,       1			)


						def   _lowerCamelCase			( self						:  Tuple      ,       _a						:  List[str]      ,       _a						:  List[str]      ,       _a						:  int			):
													a__:       List[str]											=SwinForMaskedImageModeling(config=_a			)
													model.to(_a			)
													model.eval()
													a__:       Dict											=model(_a			)
													self.parent.assertEqual(
													    result.logits.shape      ,       (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

													# test greyscale images
													a__:       Union[str, Any]											=1
													a__:       int											=SwinForMaskedImageModeling(_a			)
													model.to(_a			)
													model.eval()

													a__:       int											=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
													a__:       List[str]											=model(_a			)
													self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, 1, self.image_size, self.image_size)			)


						def   _lowerCamelCase			( self						:  Optional[Any]      ,       _a						:  List[str]      ,       _a						:  Optional[Any]      ,       _a						:  List[Any]			):
													a__:       List[Any]											=self.type_sequence_label_size
													a__:       Union[str, Any]											=SwinForImageClassification(_a			)
													model.to(_a			)
													model.eval()
													a__:       Dict											=model(_a      ,       labels=_a			)
													self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.type_sequence_label_size)			)

													# test greyscale images
													a__:       Union[str, Any]											=1
													a__:       Optional[Any]											=SwinForImageClassification(_a			)
													model.to(_a			)
													model.eval()

													a__:       List[Any]											=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
													a__:       Optional[Any]											=model(_a			)
													self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.type_sequence_label_size)			)







						def   _lowerCamelCase			( self						:  Any			):
													a__:       Dict											=self.prepare_config_and_inputs()
													(
													    (
													    a__
													)							,			(
													    a__
													)							,			(
													    a__
													)							,			
													):       Tuple											=config_and_inputs
													a__:       Dict											={"pixel_values": pixel_values}
													return config, inputs_dict


@require_torch
class 	lowerCamelCase__ (		_a				,					_a				,					unittest.TestCase   ):
						_lowerCAmelCase								= (
						    (
						        SwinModel,
						        SwinBackbone,
						        SwinForImageClassification,
						        SwinForMaskedImageModeling,
						    )
						    if is_torch_available()
						    else ()
						)
						_lowerCAmelCase								= (
						    {'''feature-extraction''': SwinModel, '''image-classification''': SwinForImageClassification}
						    if is_torch_available()
						    else {}
						)
						_lowerCAmelCase								= True

						_lowerCAmelCase								= False
						_lowerCAmelCase								= False
						_lowerCAmelCase								= False


						def   _lowerCamelCase			( self						:  Optional[Any]			):
													a__:       str											=SwinModelTester(self			)
													a__:       Optional[int]											=ConfigTester(self      ,       config_class=_a      ,       embed_dim=3_7			)


						def   _lowerCamelCase			( self						:  Optional[Any]			):
													self.create_and_test_config_common_properties()
													self.config_tester.create_and_test_config_to_json_string()
													self.config_tester.create_and_test_config_to_json_file()
													self.config_tester.create_and_test_config_from_and_save_pretrained()
													self.config_tester.create_and_test_config_with_num_labels()
													self.config_tester.check_config_can_be_init_without_params()
													self.config_tester.check_config_arguments_init()


						def   _lowerCamelCase			( self						:  Union[str, Any]			):
													return


						def   _lowerCamelCase			( self						:  Optional[int]			):
													a__:       List[str]											=self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*_a			)


						@unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0."			)
						def   _lowerCamelCase			( self						:  List[str]			):
													pass


						def   _lowerCamelCase			( self						:  List[Any]			):
													super().test_training_gradient_checkpointing()


						def   _lowerCamelCase			( self						:  str			):
													a__:       Dict											=self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_backbone(*_a			)


						def   _lowerCamelCase			( self						:  Tuple			):
													a__:       str											=self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_masked_image_modeling(*_a			)


						def   _lowerCamelCase			( self						:  List[str]			):
													a__:       Dict											=self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*_a			)


						@unittest.skip(reason="Swin does not use inputs_embeds"			)
						def   _lowerCamelCase			( self						:  int			):
													pass


						@unittest.skip(reason="Swin Transformer does not use feedforward chunking"			)
						def   _lowerCamelCase			( self						:  List[str]			):
													pass


						def   _lowerCamelCase			( self						:  str			):
													a__							,			a__:       Optional[Any]											=self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				a__:       Union[str, Any]											=model_class(_a			)
																				self.assertIsInstance(model.get_input_embeddings()      ,       (nn.Module)			)
																				a__:       int											=model.get_output_embeddings()
																				self.assertTrue(x is None or isinstance(_a      ,       nn.Linear			)			)


						def   _lowerCamelCase			( self						:  Optional[Any]			):
													a__							,			a__:       Union[str, Any]											=self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				a__:       int											=model_class(_a			)
																				a__:       Dict											=inspect.signature(model.forward			)
																				# signature.parameters is an OrderedDict => so arg_names order is deterministic
																				a__:       Tuple											=[*signature.parameters.keys()]

																				a__:       Tuple											=["pixel_values"]
																				self.assertListEqual(arg_names[:1]      ,       _a			)


						def   _lowerCamelCase			( self						:  List[Any]			):
													a__							,			a__:       List[str]											=self.model_tester.prepare_config_and_inputs_for_common()
													a__:       List[str]											=True

													for model_class in self.all_model_classes:
																				a__:       Optional[int]											=True
																				a__:       str											=False
																				a__:       Dict											=True
																				a__:       Optional[Any]											=model_class(_a			)
																				model.to(_a			)
																				model.eval()
																				with torch.no_grad():
																											a__:       List[str]											=model(**self._prepare_for_class(_a      ,       _a			)			)
																				a__:       Any											=outputs.attentions
																				a__:       str											=len(self.model_tester.depths			)
																				self.assertEqual(len(_a			)      ,       _a			)

																				# check that output_attentions also work using config
																				del inputs_dict["output_attentions"]
																				a__:       int											=True
																				a__:       List[str]											=config.window_size**2
																				a__:       int											=model_class(_a			)
																				model.to(_a			)
																				model.eval()
																				with torch.no_grad():
																											a__:       Union[str, Any]											=model(**self._prepare_for_class(_a      ,       _a			)			)
																				a__:       int											=outputs.attentions
																				self.assertEqual(len(_a			)      ,       _a			)

																				self.assertListEqual(
																				    list(attentions[0].shape[-3:]			)      ,       [self.model_tester.num_heads[0], window_size_squared, window_size_squared]      ,       )
																				a__:       Dict											=len(_a			)

																				# Check attention is always last and order is fine
																				a__:       Union[str, Any]											=True
																				a__:       Dict											=True
																				a__:       Tuple											=model_class(_a			)
																				model.to(_a			)
																				model.eval()
																				with torch.no_grad():
																											a__:       List[Any]											=model(**self._prepare_for_class(_a      ,       _a			)			)

																				# also another +1 for reshaped_hidden_states
																				a__:       Optional[Any]											=1 if model_class.__name__ == "SwinBackbone" else 2
																				self.assertEqual(out_len + added_hidden_states      ,       len(_a			)			)

																				a__:       List[str]											=outputs.attentions

																				self.assertEqual(len(_a			)      ,       _a			)

																				self.assertListEqual(
																				    list(self_attentions[0].shape[-3:]			)      ,       [self.model_tester.num_heads[0], window_size_squared, window_size_squared]      ,       )


						def   _lowerCamelCase			( self						:  Optional[int]      ,       _a						:  Tuple      ,       _a						:  str      ,       _a						:  Any      ,       _a						:  List[str]			):
													a__:       List[Any]											=model_class(_a			)
													model.to(_a			)
													model.eval()

													with torch.no_grad():
																				a__:       Optional[int]											=model(**self._prepare_for_class(_a      ,       _a			)			)

													a__:       Tuple											=outputs.hidden_states

													a__:       Optional[int]											=getattr(
													    self.model_tester      ,       "expected_num_hidden_layers"      ,       len(self.model_tester.depths			) + 1			)
													self.assertEqual(len(_a			)      ,       _a			)

													# Swin has a different seq_length
													a__:       int											=(
													    config.patch_size
													    if isinstance(config.patch_size      ,       collections.abc.Iterable			)
													    else (config.patch_size, config.patch_size)
													)

													a__:       List[str]											=(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

													self.assertListEqual(
													    list(hidden_states[0].shape[-2:]			)      ,       [num_patches, self.model_tester.embed_dim]      ,       )

													if not model_class.__name__ == "SwinBackbone":
																				a__:       Any											=outputs.reshaped_hidden_states
																				self.assertEqual(len(_a			)      ,       _a			)

																				a__							,			a__							,			a__							,			a__:       Tuple											=reshaped_hidden_states[0].shape
																				a__:       Tuple											=(
																				    reshaped_hidden_states[0].view(_a      ,       _a      ,       height * width			).permute(0      ,       2      ,       1			)
																				)
																				self.assertListEqual(
																				    list(reshaped_hidden_states.shape[-2:]			)      ,       [num_patches, self.model_tester.embed_dim]      ,       )


						def   _lowerCamelCase			( self						:  List[Any]			):
													a__							,			a__:       List[str]											=self.model_tester.prepare_config_and_inputs_for_common()

													a__:       Dict											=(
													    self.model_tester.image_size
													    if isinstance(self.model_tester.image_size      ,       collections.abc.Iterable			)
													    else (self.model_tester.image_size, self.model_tester.image_size)
													)

													for model_class in self.all_model_classes:
																				a__:       Any											=True
																				self.check_hidden_states_output(_a      ,       _a      ,       _a      ,       _a			)

																				# check that output_hidden_states also work using config
																				del inputs_dict["output_hidden_states"]
																				a__:       List[Any]											=True

																				self.check_hidden_states_output(_a      ,       _a      ,       _a      ,       _a			)


						def   _lowerCamelCase			( self						:  Dict			):
													a__							,			a__:       Dict											=self.model_tester.prepare_config_and_inputs_for_common()
													a__:       int											=3

													a__:       List[Any]											=(
													    self.model_tester.image_size
													    if isinstance(self.model_tester.image_size      ,       collections.abc.Iterable			)
													    else (self.model_tester.image_size, self.model_tester.image_size)
													)
													a__:       Optional[int]											=(
													    config.patch_size
													    if isinstance(config.patch_size      ,       collections.abc.Iterable			)
													    else (config.patch_size, config.patch_size)
													)

													a__:       List[Any]											=image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
													a__:       List[str]											=image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

													for model_class in self.all_model_classes:
																				a__:       Dict											=True
																				self.check_hidden_states_output(_a      ,       _a      ,       _a      ,       (padded_height, padded_width)			)

																				# check that output_hidden_states also work using config
																				del inputs_dict["output_hidden_states"]
																				a__:       Optional[int]											=True
																				self.check_hidden_states_output(_a      ,       _a      ,       _a      ,       (padded_height, padded_width)			)


						@slow
						def   _lowerCamelCase			( self						:  List[Any]			):
													for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				a__:       Optional[int]											=SwinModel.from_pretrained(_a			)
																				self.assertIsNotNone(_a			)







						def   _lowerCamelCase			( self						:  Tuple			):
													a__							,			a__:       int											=self.model_tester.prepare_config_and_inputs_for_common()

													a__:       Dict											=_config_zero_init(_a			)
													for model_class in self.all_model_classes:
																				a__:       Optional[int]											=model_class(config=_a			)
																				for name, param in model.named_parameters():
																											if "embeddings" not in name and param.requires_grad:
																																		self.assertIn(
																																		    ((param.data.mean() * 1e9).round() / 1e9).item()      ,       [0.0, 1.0]      ,       msg=F"Parameter {name} of model {model_class} seems not properly initialized"      ,       )


@require_vision
@require_torch
class 	lowerCamelCase__ (		unittest.TestCase   ):


						@cached_property
						def   _lowerCamelCase			( self						:  int			):
													return (
													    AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224"			)
													    if is_vision_available()
													    else None
													)







						@slow
						def   _lowerCamelCase			( self						:  List[Any]			):
													a__:       Tuple											=SwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224"			).to(_a			)
													a__:       Dict											=self.default_image_processor

													a__:       Any											=Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
													a__:       Optional[Any]											=image_processor(images=_a      ,       return_tensors="pt"			).to(_a			)

													# forward pass
													with torch.no_grad():
																				a__:       Any											=model(**_a			)

													# verify the logits
													a__:       Optional[int]											=torch.Size((1, 1_0_0_0)			)
													self.assertEqual(outputs.logits.shape      ,       _a			)
													a__:       Any											=torch.tensor([-0.0_9_4_8, -0.6_4_5_4, -0.0_9_2_1]			).to(_a			)
													self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,       _a      ,       atol=1e-4			)			)


@require_torch
class 	lowerCamelCase__ (		unittest.TestCase				,					_a   ):
						_lowerCAmelCase								= (SwinBackbone,) if is_torch_available() else ()
						_lowerCAmelCase								= SwinConfig


						def   _lowerCamelCase			( self						:  int			):
													a__:       Tuple											=SwinModelTester(self			)










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

__UpperCAmelCase						  =     logging.get_logger(__name__)





def 						__lowerCamelCase       (      __magic_name__	:  bytes     , __magic_name__	:  int						):
							a__:       Optional[int]											=F"{sampling_rate}"
							a__:       Union[str, Any]											="1"
							a__:       List[str]											="f32le"
							a__:       Dict											=[
							    "ffmpeg",
							    "-i",
							    "pipe:0",
							    "-ac",
							    ac,
							    "-ar",
							    ar,
							    "-f",
							    format_for_conversion,
							    "-hide_banner",
							    "-loglevel",
							    "quiet",
							    "pipe:1",
							]

							try:
														a__:       List[Any]											=subprocess.Popen(__magic_name__     , stdin=subprocess.PIPE     , stdout=subprocess.PIPE						)
							except FileNotFoundError:
														raise ValueError("ffmpeg was not found but is required to load audio files from filename"						)
							a__:       int											=ffmpeg_process.communicate(__magic_name__						)
							a__:       List[str]											=output_stream[0]

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







@add_end_docstrings(_a   )
class 	lowerCamelCase__ (		_a   ):


						def __init__( self						:  Union[str, Any]      ,       *_a						:  Dict      ,       **_a						:  Tuple			):
													# Default, might be overriden by the model.config.
													a__:       List[Any]											=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						:  Tuple      ,       _a						:  Union[np.ndarray, bytes, str]      ,       **_a						:  Union[str, Any]      ,       ):
													return super().__call__(_a      ,       **_a			)


						def   _lowerCamelCase			( self						:  int      ,       _a						:  Tuple=None      ,       **_a						:  int			):
													# No parameters on this pipeline right now
													a__:       Optional[int]											={}
													if top_k is not None:
																				if top_k > self.model.config.num_labels:
																											a__:       Union[str, Any]											=self.model.config.num_labels
																				a__:       Union[str, Any]											=top_k
													return {}, {}, postprocess_params


						def   _lowerCamelCase			( self						:  Any      ,       _a						:  Union[str, Any]			):
													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
																											a__:       List[str]											=requests.get(_a			).content
																				else:
																											with open(_a      ,       "rb"			) as f:
																																		a__:       Dict											=f.read()

													if isinstance(_a      ,       _a			):
																				a__:       Tuple											=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"			)

																				a__:       Tuple											=inputs.pop("raw"      ,       _a			)
																				if _inputs is None:
																											# Remove path which will not be used from `datasets`.
																											inputs.pop("path"      ,       _a			)
																											a__:       int											=inputs.pop("array"      ,       _a			)
																				a__:       Optional[Any]											=inputs.pop("sampling_rate"			)
																				a__:       Optional[int]											=_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`."			)

																											a__:       Union[str, Any]											=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"			)

													a__:       Union[str, Any]											=self.feature_extractor(
													    _a      ,       sampling_rate=self.feature_extractor.sampling_rate      ,       return_tensors="pt"			)
													return processed


						def   _lowerCamelCase			( self						:  Dict      ,       _a						:  Tuple			):
													a__:       str											=self.model(**_a			)
													return model_outputs







						def   _lowerCamelCase			( self						:  Optional[Any]      ,       _a						:  Tuple      ,       _a						:  Tuple=5			):
													a__:       Tuple											=model_outputs.logits[0].softmax(-1			)
													a__							,			a__:       Any											=probs.topk(_a			)

													a__:       Union[str, Any]											=scores.tolist()
													a__:       Dict											=ids.tolist()

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

													return labels





