

'''simple docstring'''





import unittest

import numpy as np

from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
from transformers.pipelines import AudioClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torchaudio,
    slow,
)

from .test_pipelines_common import ANY





@is_pipeline_test
class 		__SCREAMING_SNAKE_CASE							(			unittest.TestCase      ):
				lowerCamelCase_		       =    MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
				lowerCamelCase_		       =    TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING







				def  lowerCamelCase_	(       self     :		Optional[int]		,					UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		Optional[int]		,					UpperCAmelCase__     :		Any   ):
										'''simple docstring'''
										lowercase :							str    		=AudioClassificationPipeline(model=UpperCAmelCase__		,					feature_extractor=UpperCAmelCase__   )

										# test with a raw waveform
										lowercase :							Dict    		=np.zeros((34000,)   )
										lowercase :							List[Any]    		=np.zeros((14000,)   )
										return audio_classifier, [audioa, audio]







				def  lowerCamelCase_	(       self     :		str		,					UpperCAmelCase__     :		str		,					UpperCAmelCase__     :		Tuple   ):
										'''simple docstring'''
										lowercase		,	lowercase :							Union[str, Any]    		=examples
										lowercase :							Union[str, Any]    		=audio_classifier(UpperCAmelCase__   )
										# by default a model is initialized with num_labels=2
										self.assertEqual(
										    UpperCAmelCase__		,					[
										        {'''score''': ANY(UpperCAmelCase__   ), '''label''': ANY(UpperCAmelCase__   )},
										        {'''score''': ANY(UpperCAmelCase__   ), '''label''': ANY(UpperCAmelCase__   )},
										    ]		,					)
										lowercase :							List[str]    		=audio_classifier(UpperCAmelCase__		,					top_k=1   )
										self.assertEqual(
										    UpperCAmelCase__		,					[
										        {'''score''': ANY(UpperCAmelCase__   ), '''label''': ANY(UpperCAmelCase__   )},
										    ]		,					)

										self.run_torchaudio(UpperCAmelCase__   )







				@require_torchaudio
				def  lowerCamelCase_	(       self     :		str		,					UpperCAmelCase__     :		Optional[int]   ):
										'''simple docstring'''
										import datasets

										# test with a local file
										lowercase :							Optional[int]    		=datasets.load_dataset('''hf-internal-testing/librispeech_asr_dummy'''		,					'''clean'''		,					split='''validation'''   )
										lowercase :							str    		=dataset[0]['''audio''']['''array''']
										lowercase :							Tuple    		=audio_classifier(UpperCAmelCase__   )
										self.assertEqual(
										    UpperCAmelCase__		,					[
										        {'''score''': ANY(UpperCAmelCase__   ), '''label''': ANY(UpperCAmelCase__   )},
										        {'''score''': ANY(UpperCAmelCase__   ), '''label''': ANY(UpperCAmelCase__   )},
										    ]		,					)







				@require_torch
				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							List[Any]    		='''anton-l/wav2vec2-random-tiny-classifier'''

										lowercase :							Any    		=pipeline('''audio-classification'''		,					model=UpperCAmelCase__   )

										lowercase :							Any    		=np.ones((8000,)   )
										lowercase :							Tuple    		=audio_classifier(UpperCAmelCase__		,					top_k=4   )

										lowercase :							Any    		=[
										    {'''score''': 0.08_42, '''label''': '''no'''},
										    {'''score''': 0.08_38, '''label''': '''up'''},
										    {'''score''': 0.08_37, '''label''': '''go'''},
										    {'''score''': 0.08_34, '''label''': '''right'''},
										]
										lowercase :							str    		=[
										    {'''score''': 0.08_45, '''label''': '''stop'''},
										    {'''score''': 0.08_44, '''label''': '''on'''},
										    {'''score''': 0.08_41, '''label''': '''right'''},
										    {'''score''': 0.08_34, '''label''': '''left'''},
										]
										self.assertIn(nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]   )

										lowercase :							Optional[int]    		={'''array''': np.ones((8000,)   ), '''sampling_rate''': audio_classifier.feature_extractor.sampling_rate}
										lowercase :							Union[str, Any]    		=audio_classifier(UpperCAmelCase__		,					top_k=4   )
										self.assertIn(nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]   )







				@require_torch
				@slow
				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										import datasets

										lowercase :							List[Any]    		='''superb/wav2vec2-base-superb-ks'''

										lowercase :							str    		=pipeline('''audio-classification'''		,					model=UpperCAmelCase__   )
										lowercase :							Optional[int]    		=datasets.load_dataset('''anton-l/superb_dummy'''		,					'''ks'''		,					split='''test'''   )

										lowercase :							Optional[int]    		=np.array(dataset[3]['''speech''']		,					dtype=np.floataa   )
										lowercase :							Optional[Any]    		=audio_classifier(UpperCAmelCase__		,					top_k=4   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=3   )		,					[
										        {'''score''': 0.9_81, '''label''': '''go'''},
										        {'''score''': 0.0_07, '''label''': '''up'''},
										        {'''score''': 0.0_06, '''label''': '''_unknown_'''},
										        {'''score''': 0.0_01, '''label''': '''down'''},
										    ]		,					)







				@require_tf
				@unittest.skip('''Audio classification is not implemented for TF'''   )
				def  lowerCamelCase_	(       self     :		List[Any]   ):
										'''simple docstring'''
										pass








'''simple docstring'''





from typing import Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format
from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images
from ...utils import TensorType, logging


UpperCamelCase_    						=       logging.get_logger(__name__)





class 		__SCREAMING_SNAKE_CASE							(			lowercase__      ):
				lowerCamelCase_		       =    ['pixel_values']







				def __init__(       self     :		List[Any]		,					UpperCAmelCase__     :		bool = True		,					UpperCAmelCase__     :		Union[int, float] = 1 / 255		,					UpperCAmelCase__     :		bool = True		,					UpperCAmelCase__     :		int = 8		,					**UpperCAmelCase__     :		str		,					):
										'''simple docstring'''
										super().__init__(**UpperCAmelCase__   )

										lowercase :							Union[str, Any]    		=do_rescale
										lowercase :							List[Any]    		=rescale_factor
										lowercase :							Tuple    		=do_pad
										lowercase :							List[str]    		=pad_size







				def  lowerCamelCase_	(       self     :		List[str]		,					UpperCAmelCase__     :		np.ndarray		,					UpperCAmelCase__     :		float		,					UpperCAmelCase__     :		Optional[Union[str, ChannelDimension]] = None		,					**UpperCAmelCase__     :		Optional[int]   ):
										'''simple docstring'''
										return rescale(UpperCAmelCase__		,					scale=UpperCAmelCase__		,					data_format=UpperCAmelCase__		,					**UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		Tuple		,					UpperCAmelCase__     :		np.ndarray		,					UpperCAmelCase__     :		int		,					UpperCAmelCase__     :		Optional[Union[str, ChannelDimension]] = None   ):
										'''simple docstring'''
										lowercase		,	lowercase :							Union[str, Any]    		=get_image_size(UpperCAmelCase__   )
										lowercase :							Tuple    		=(old_height // size + 1) * size - old_height
										lowercase :							Tuple    		=(old_width // size + 1) * size - old_width

										return pad(UpperCAmelCase__		,					((0, pad_height), (0, pad_width))		,					mode='''symmetric'''		,					data_format=UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		List[str]		,					UpperCAmelCase__     :		ImageInput		,					UpperCAmelCase__     :		Optional[bool] = None		,					UpperCAmelCase__     :		Optional[float] = None		,					UpperCAmelCase__     :		Optional[bool] = None		,					UpperCAmelCase__     :		Optional[int] = None		,					UpperCAmelCase__     :		Optional[Union[str, TensorType]] = None		,					UpperCAmelCase__     :		Union[str, ChannelDimension] = ChannelDimension.FIRST		,					**UpperCAmelCase__     :		Optional[Any]		,					):
										'''simple docstring'''
										lowercase :							int    		=do_rescale if do_rescale is not None else self.do_rescale
										lowercase :							Tuple    		=rescale_factor if rescale_factor is not None else self.rescale_factor
										lowercase :							int    		=do_pad if do_pad is not None else self.do_pad
										lowercase :							List[Any]    		=pad_size if pad_size is not None else self.pad_size

										lowercase :							Any    		=make_list_of_images(UpperCAmelCase__   )

										if not valid_images(UpperCAmelCase__   ):
																raise ValueError(
																    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
																    '''torch.Tensor, tf.Tensor or jax.ndarray.'''   )

										if do_rescale and rescale_factor is None:
																raise ValueError('''Rescale factor must be specified if do_rescale is True.'''   )

										# All transformations expect numpy arrays.
										lowercase :							Dict    		=[to_numpy_array(UpperCAmelCase__   ) for image in images]

										if do_rescale:
																lowercase :							Tuple    		=[self.rescale(image=UpperCAmelCase__		,					scale=UpperCAmelCase__   ) for image in images]

										if do_pad:
																lowercase :							Union[str, Any]    		=[self.pad(UpperCAmelCase__		,					size=UpperCAmelCase__   ) for image in images]

										lowercase :							Dict    		=[to_channel_dimension_format(UpperCAmelCase__		,					UpperCAmelCase__   ) for image in images]

										lowercase :							Any    		={'''pixel_values''': images}
										return BatchFeature(data=UpperCAmelCase__		,					tensor_type=UpperCAmelCase__   )





