

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   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			_UpperCAmelCase   :							Optional[int]										=     MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
			_UpperCAmelCase   :							int										=     TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING



			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     Dict):
									SCREAMING_SNAKE_CASE_: Any  		=       AudioClassificationPipeline(model=lowerCAmelCase__   ,						feature_extractor=lowerCAmelCase__)

									# test with a raw waveform
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       np.zeros((3_4000,))
									SCREAMING_SNAKE_CASE_: List[Any]  		=       np.zeros((1_4000,))
									return audio_classifier, [audioa, audio]



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Any  		=       examples
									SCREAMING_SNAKE_CASE_: List[str]  		=       audio_classifier(lowerCAmelCase__)
									# by default a model is initialized with num_labels=2
									self.assertEqual(
									    lowerCAmelCase__   ,						[
									        {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)},
									        {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)},
									    ]   ,						)
									SCREAMING_SNAKE_CASE_: Dict  		=       audio_classifier(lowerCAmelCase__   ,						top_k=1)
									self.assertEqual(
									    lowerCAmelCase__   ,						[
									        {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)},
									    ]   ,						)

									self.run_torchaudio(lowerCAmelCase__)



			@require_torchaudio
			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]   ,						lowerCAmelCase__  :     Dict):
									import datasets

									# test with a local file
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy"   ,						"clean"   ,						split="validation")
									SCREAMING_SNAKE_CASE_: List[Any]  		=       dataset[0]["audio"]["array"]
									SCREAMING_SNAKE_CASE_: Tuple  		=       audio_classifier(lowerCAmelCase__)
									self.assertEqual(
									    lowerCAmelCase__   ,						[
									        {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)},
									        {"score": ANY(lowerCAmelCase__), "label": ANY(lowerCAmelCase__)},
									    ]   ,						)



			@require_torch
			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									SCREAMING_SNAKE_CASE_: List[str]  		=       "anton-l/wav2vec2-random-tiny-classifier"

									SCREAMING_SNAKE_CASE_: Tuple  		=       pipeline("audio-classification"   ,						model=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       np.ones((8000,))
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       audio_classifier(lowerCAmelCase__   ,						top_k=4)

									SCREAMING_SNAKE_CASE_: List[Any]  		=       [
									    {"score": 0.0842, "label": "no"},
									    {"score": 0.0838, "label": "up"},
									    {"score": 0.0837, "label": "go"},
									    {"score": 0.0834, "label": "right"},
									]
									SCREAMING_SNAKE_CASE_: List[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(lowerCAmelCase__   ,						decimals=4)   ,						[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2])

									SCREAMING_SNAKE_CASE_: int  		=       {"array": np.ones((8000,)), "sampling_rate": audio_classifier.feature_extractor.sampling_rate}
									SCREAMING_SNAKE_CASE_: str  		=       audio_classifier(lowerCAmelCase__   ,						top_k=4)
									self.assertIn(nested_simplify(lowerCAmelCase__   ,						decimals=4)   ,						[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2])



			@require_torch
			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									import datasets

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       "superb/wav2vec2-base-superb-ks"

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       pipeline("audio-classification"   ,						model=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Any  		=       datasets.load_dataset("anton-l/superb_dummy"   ,						"ks"   ,						split="test")

									SCREAMING_SNAKE_CASE_: List[Any]  		=       np.array(dataset[3]["speech"]   ,						dtype=np.floataa)
									SCREAMING_SNAKE_CASE_: str  		=       audio_classifier(lowerCAmelCase__   ,						top_k=4)
									self.assertEqual(
									    nested_simplify(lowerCAmelCase__   ,						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        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									pass







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


A   :     Tuple       =				DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

A   :     Dict       =				"main"
# Default branch name
A   :     List[str]       =				"f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
A   :     Tuple       =				"aaaaaaa"
# This commit does not exist, so we should 404.

A   :     int       =				"d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
A   :     Tuple       =				"4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"


@contextlib.contextmanager
def    a__       (						):
      print("Welcome!" )
      yield
      print("Bye!" )


@contextlib.contextmanager
def    a__       (						):
      print("Bonjour!" )
      yield
      print("Au revoir!" )


class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  def       __A   (							self       :				Union[str, Any]      )     ->		Any:
        # If the spec is missing, importlib would not be able to import the module dynamically.
        assert transformers.__spec__ is not None
        assert importlib.util.find_spec("transformers"      ) is not None



class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Union[str, Any]      )     ->		Union[str, Any]:
        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       __A   (							self       :				Dict     ,   __magic_name__       :				Union[str, Any]      )     ->		int:
        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       __A   (							self       :				Tuple     ,   __magic_name__       :				str      )     ->		Union[str, Any]:
        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       __A   (							self       :				List[str]      )     ->		Union[str, Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



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







  @require_tf
  def       __A   (							self       :				List[str]      )     ->		Optional[Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



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







  @require_flax
  def       __A   (							self       :				int      )     ->		Tuple:
        # Flax models don't have labels
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



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


