





"""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 					__UpperCAmelCase							(						unittest.TestCase  ):
				__lowerCamelCase				:	Union[str, Any]				     =				MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
				__lowerCamelCase				:	Optional[Any]				     =				TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
				def       UpperCAmelCase      (		self    :			Union[str, Any]	, a_    :			Any	, a_    :			str	, a_    :			Optional[Any]    )	->	List[Any]:



							'''simple docstring'''



							a__  :	int		 =			AudioClassificationPipeline(model=a_	, feature_extractor=a_    )

							# test with a raw waveform
							a__  :	Optional[int]		 =			np.zeros((3_40_00,)    )
							a__  :	Dict		 =			np.zeros((1_40_00,)    )
							return audio_classifier, [audioa, audio]
				def       UpperCAmelCase      (		self    :			Optional[int]	, a_    :			List[Any]	, a_    :			Any    )	->	Tuple:



							'''simple docstring'''



							a__  :	Optional[Any]		 =			examples
							a__  :	Any		 =			audio_classifier(a_    )
							# by default a model is initialized with num_labels=2
							self.assertEqual(
							    a_	, [
							        {"score": ANY(a_    ), "label": ANY(a_    )},
							        {"score": ANY(a_    ), "label": ANY(a_    )},
							    ]	, )
							a__  :	str		 =			audio_classifier(a_	, top_k=1    )
							self.assertEqual(
							    a_	, [
							        {"score": ANY(a_    ), "label": ANY(a_    )},
							    ]	, )

							self.run_torchaudio(a_    )
				@require_torchaudio
				def       UpperCAmelCase      (		self    :			List[Any]	, a_    :			Tuple    )	->	Any:



							'''simple docstring'''



							import datasets

							# test with a local file
							a__  :	List[str]		 =			datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy"	, "clean"	, split="validation"    )
							a__  :	Dict		 =			dataset[0]["audio"]["array"]
							a__  :	int		 =			audio_classifier(a_    )
							self.assertEqual(
							    a_	, [
							        {"score": ANY(a_    ), "label": ANY(a_    )},
							        {"score": ANY(a_    ), "label": ANY(a_    )},
							    ]	, )
				@require_torch
				def       UpperCAmelCase      (		self    :			int    )	->	List[str]:



							'''simple docstring'''



							a__  :	str		 =			"anton-l/wav2vec2-random-tiny-classifier"

							a__  :	Tuple		 =			pipeline("audio-classification"	, model=a_    )

							a__  :	str		 =			np.ones((80_00,)    )
							a__  :	List[str]		 =			audio_classifier(a_	, top_k=4    )

							a__  :	Union[str, Any]		 =			[
							    {"score": 0.0842, "label": "no"},
							    {"score": 0.0838, "label": "up"},
							    {"score": 0.0837, "label": "go"},
							    {"score": 0.0834, "label": "right"},
							]
							a__  :	Optional[Any]		 =			[
							    {"score": 0.0845, "label": "stop"},
							    {"score": 0.0844, "label": "on"},
							    {"score": 0.0841, "label": "right"},
							    {"score": 0.0834, "label": "left"},
							]
							self.assertIn(nested_simplify(a_	, decimals=4    )	, [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]    )

							a__  :	Optional[Any]		 =			{"array": np.ones((80_00,)    ), "sampling_rate": audio_classifier.feature_extractor.sampling_rate}
							a__  :	Optional[Any]		 =			audio_classifier(a_	, top_k=4    )
							self.assertIn(nested_simplify(a_	, decimals=4    )	, [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]    )
				@require_torch
				@slow
				def       UpperCAmelCase      (		self    :			Optional[Any]    )	->	Union[str, Any]:



							'''simple docstring'''



							import datasets

							a__  :	Union[str, Any]		 =			"superb/wav2vec2-base-superb-ks"

							a__  :	Tuple		 =			pipeline("audio-classification"	, model=a_    )
							a__  :	List[str]		 =			datasets.load_dataset("anton-l/superb_dummy"	, "ks"	, split="test"    )

							a__  :	List[Any]		 =			np.array(dataset[3]["speech"]	, dtype=np.floataa    )
							a__  :	Any		 =			audio_classifier(a_	, top_k=4    )
							self.assertEqual(
							    nested_simplify(a_	, decimals=3    )	, [
							        {"score": 0.981, "label": "go"},
							        {"score": 0.007, "label": "up"},
							        {"score": 0.006, "label": "_unknown_"},
							        {"score": 0.001, "label": "down"},
							    ]	, )






				@require_tf
				@unittest.skip("Audio classification is not implemented for TF"    )
				def       UpperCAmelCase      (		self    :			str    )	->	Any:



							'''simple docstring'''



							pass







'''simple docstring'''
import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
 from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
 from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
 from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


UpperCamelCase__			=      DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

UpperCamelCase__			=      'main'
# Default branch name
UpperCamelCase__			=      'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'
# One particular commit (not the top of `main`)
UpperCamelCase__			=      'aaaaaaa'
# This commit does not exist, so we should 404.

UpperCamelCase__			=      'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684'
# Sha-1 of config.json on the top of `main`, for checking purposes
UpperCamelCase__			=      '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'




@contextlib.contextmanager
def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   print("Welcome!"				)
   yield
   print("Bye!"				)




@contextlib.contextmanager
def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   print("Bonjour!"				)
   yield
   print("Au revoir!"				)


class 							_UpperCAmelCase    (		unittest.TestCase      ):




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       assert transformers.__spec__ is not None
       assert importlib.util.find_spec("transformers"      ) is not None


class 							_UpperCAmelCase    (		unittest.TestCase      ):




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							str	,  a	:							List[str]      ):






       '''simple docstring'''






       with ContextManagers([]      ):
          print("Transformers are awesome!"      )
       # The print statement adds a new line at the end of the output
       self.assertEqual(mock_stdout.getvalue()	,  "Transformers are awesome!\n"      )




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							List[str]	,  a	:							Optional[int]      ):






       '''simple docstring'''






       with ContextManagers([context_en()]      ):
          print("Transformers are awesome!"      )
       # The output should be wrapped with an English welcome and goodbye
       self.assertEqual(mock_stdout.getvalue()	,  "Welcome!\nTransformers are awesome!\nBye!\n"      )




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							Tuple	,  a	:							List[Any]      ):






       '''simple docstring'''






       with ContextManagers([context_fr(), context_en()]      ):
          print("Transformers are awesome!"      )
       # The output should be wrapped with an English and French welcome and goodbye
       self.assertEqual(mock_stdout.getvalue()	,  "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"      )




    @require_torch
    def 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  ["labels"]      )
       self.assertEqual(find_labels(a      )	,  ["labels", "next_sentence_label"]      )
       self.assertEqual(find_labels(a      )	,  ["start_positions", "end_positions"]      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  ["labels"]      )




    @require_tf
    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  ["labels"]      )
       self.assertEqual(find_labels(a      )	,  ["labels", "next_sentence_label"]      )
       self.assertEqual(find_labels(a      )	,  ["start_positions", "end_positions"]      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  ["labels"]      )





    @require_flax
    def 					lowerCAmelCase__					(      self	:							str      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  []      )
       self.assertEqual(find_labels(a      )	,  []      )
       self.assertEqual(find_labels(a      )	,  []      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  []      )




