





import shutil
import tempfile
import unittest

from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast
from transformers.testing_utils import require_sentencepiece, require_torchaudio

from .test_feature_extraction_clap import floats_list



@require_torchaudio
@require_sentencepiece
class 							_UpperCAmelCase       (       unittest.TestCase       ):

  """simple docstring"""


  def 							lowercase						(							self					:						Union[str, Any]	)				->		Any:
     __lowerCAmelCase				      =      'laion/clap-htsat-unfused'
     __lowerCAmelCase				      =      tempfile.mkdtemp()






  def 							lowercase						(							self					:						Optional[int]   ,    **lowerCAmelCase_					:						Union[str, Any]	)				->		Optional[int]:
     return RobertaTokenizer.from_pretrained(self.checkpoint   ,    **lowerCAmelCase_	)






  def 							lowercase						(							self					:						str   ,    **lowerCAmelCase_					:						Optional[int]	)				->		List[str]:
     return ClapFeatureExtractor.from_pretrained(self.checkpoint   ,    **lowerCAmelCase_	)






  def 							lowercase						(							self					:						int	)				->		Union[str, Any]:
     shutil.rmtree(self.tmpdirname	)






  def 							lowercase						(							self					:						Union[str, Any]	)				->		Dict:
     __lowerCAmelCase				      =      self.get_tokenizer()
     __lowerCAmelCase				      =      self.get_feature_extractor()

     __lowerCAmelCase				      =      ClapProcessor(tokenizer=lowerCAmelCase_   ,    feature_extractor=lowerCAmelCase_	)

     processor.save_pretrained(self.tmpdirname	)
     __lowerCAmelCase				      =      ClapProcessor.from_pretrained(self.tmpdirname	)

     self.assertEqual(processor.tokenizer.get_vocab()   ,    tokenizer.get_vocab()	)
     self.assertIsInstance(processor.tokenizer   ,    lowerCAmelCase_	)

     self.assertEqual(processor.feature_extractor.to_json_string()   ,    feature_extractor.to_json_string()	)
     self.assertIsInstance(processor.feature_extractor   ,    lowerCAmelCase_	)






  def 							lowercase						(							self					:						str	)				->		List[Any]:
     __lowerCAmelCase				      =      ClapProcessor(tokenizer=self.get_tokenizer()   ,    feature_extractor=self.get_feature_extractor()	)
     processor.save_pretrained(self.tmpdirname	)

     __lowerCAmelCase				      =      self.get_tokenizer(bos_token='(BOS)'   ,    eos_token='(EOS)'	)
     __lowerCAmelCase				      =      self.get_feature_extractor(do_normalize=lowerCAmelCase_   ,    padding_value=1.0	)

     __lowerCAmelCase				      =      ClapProcessor.from_pretrained(
         self.tmpdirname   ,    bos_token='(BOS)'   ,    eos_token='(EOS)'   ,    do_normalize=lowerCAmelCase_   ,    padding_value=1.0	)

     self.assertEqual(processor.tokenizer.get_vocab()   ,    tokenizer_add_kwargs.get_vocab()	)
     self.assertIsInstance(processor.tokenizer   ,    lowerCAmelCase_	)

     self.assertEqual(processor.feature_extractor.to_json_string()   ,    feature_extractor_add_kwargs.to_json_string()	)
     self.assertIsInstance(processor.feature_extractor   ,    lowerCAmelCase_	)






  def 							lowercase						(							self					:						Any	)				->		Dict:
     __lowerCAmelCase				      =      self.get_feature_extractor()
     __lowerCAmelCase				      =      self.get_tokenizer()

     __lowerCAmelCase				      =      ClapProcessor(tokenizer=lowerCAmelCase_   ,    feature_extractor=lowerCAmelCase_	)

     __lowerCAmelCase				      =      floats_list((3, 1_0_0_0)	)

     __lowerCAmelCase				      =      feature_extractor(lowerCAmelCase_   ,    return_tensors='np'	)
     __lowerCAmelCase				      =      processor(audios=lowerCAmelCase_   ,    return_tensors='np'	)

     for key in input_feat_extract.keys():
        self.assertAlmostEqual(input_feat_extract[key].sum()   ,    input_processor[key].sum()   ,    delta=1e-2	)






  def 							lowercase						(							self					:						Dict	)				->		Optional[int]:
     __lowerCAmelCase				      =      self.get_feature_extractor()
     __lowerCAmelCase				      =      self.get_tokenizer()

     __lowerCAmelCase				      =      ClapProcessor(tokenizer=lowerCAmelCase_   ,    feature_extractor=lowerCAmelCase_	)

     __lowerCAmelCase				      =      'This is a test string'

     __lowerCAmelCase				      =      processor(text=lowerCAmelCase_	)

     __lowerCAmelCase				      =      tokenizer(lowerCAmelCase_	)

     for key in encoded_tok.keys():
        self.assertListEqual(encoded_tok[key]   ,    encoded_processor[key]	)






  def 							lowercase						(							self					:						Union[str, Any]	)				->		str:
     __lowerCAmelCase				      =      self.get_feature_extractor()
     __lowerCAmelCase				      =      self.get_tokenizer()

     __lowerCAmelCase				      =      ClapProcessor(tokenizer=lowerCAmelCase_   ,    feature_extractor=lowerCAmelCase_	)

     __lowerCAmelCase				      =      [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

     __lowerCAmelCase				      =      processor.batch_decode(lowerCAmelCase_	)
     __lowerCAmelCase				      =      tokenizer.batch_decode(lowerCAmelCase_	)

     self.assertListEqual(lowerCAmelCase_   ,    lowerCAmelCase_	)






  def 							lowercase						(							self					:						int	)				->		Dict:
     __lowerCAmelCase				      =      self.get_feature_extractor()
     __lowerCAmelCase				      =      self.get_tokenizer()

     __lowerCAmelCase				      =      ClapProcessor(tokenizer=lowerCAmelCase_   ,    feature_extractor=lowerCAmelCase_	)

     self.assertListEqual(
         processor.model_input_names[2:]   ,    feature_extractor.model_input_names   ,    msg='`processor` and `feature_extractor` model input names do not match'   ,    )









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							):



	'''simple docstring'''




	lowerCAmelCase						=					MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
	lowerCAmelCase						=					TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING




	def 				_UpperCamelCase     (			self			,     a			,     a			,     a   )			->       Union[str, Any]:
								snake_case_           =				AudioClassificationPipeline(model=a			,     feature_extractor=a   )

								# test with a raw waveform
								snake_case_           =				np.zeros((3_40_00,)   )
								snake_case_           =				np.zeros((1_40_00,)   )
								return audio_classifier, [audioa, audio]




	def 				_UpperCamelCase     (			self			,     a			,     a   )			->       Tuple:
								snake_case_     ,						snake_case_           =				examples
								snake_case_           =				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   )},
								    ]			,     )
								snake_case_           =				audio_classifier(a			,     top_k=1   )
								self.assertEqual(
								    a			,     [
								        {'score': ANY(a   ), 'label': ANY(a   )},
								    ]			,     )

								self.run_torchaudio(a   )




	@require_torchaudio
	def 				_UpperCamelCase     (			self			,     a   )			->       List[str]:
								import datasets

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




	@require_torch
	def 				_UpperCamelCase     (			self   )			->       Dict:
								snake_case_           =				'anton-l/wav2vec2-random-tiny-classifier'

								snake_case_           =				pipeline('audio-classification'			,     model=a   )

								snake_case_           =				np.ones((80_00,)   )
								snake_case_           =				audio_classifier(a			,     top_k=4   )

								snake_case_           =				[
								    {'score': 0.0_842, 'label': 'no'},
								    {'score': 0.0_838, 'label': 'up'},
								    {'score': 0.0_837, 'label': 'go'},
								    {'score': 0.0_834, 'label': 'right'},
								]
								snake_case_           =				[
								    {'score': 0.0_845, 'label': 'stop'},
								    {'score': 0.0_844, 'label': 'on'},
								    {'score': 0.0_841, 'label': 'right'},
								    {'score': 0.0_834, 'label': 'left'},
								]
								self.assertIn(nested_simplify(a			,     decimals=4   )			,     [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]   )

								snake_case_           =				{'array': np.ones((80_00,)   ), 'sampling_rate': audio_classifier.feature_extractor.sampling_rate}
								snake_case_           =				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   )			->       str:
								import datasets

								snake_case_           =				'superb/wav2vec2-base-superb-ks'

								snake_case_           =				pipeline('audio-classification'			,     model=a   )
								snake_case_           =				datasets.load_dataset('anton-l/superb_dummy'			,     'ks'			,     split='test'   )

								snake_case_           =				np.array(dataset[3]['speech']			,     dtype=np.floataa   )
								snake_case_           =				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   )			->       Optional[int]:
								pass





