






'''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  ):
      __a	       =MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
      __a	       =TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase   )				->Union[str, Any]:



         '''simple docstring'''
         __a					  =     AudioClassificationPipeline(model=lowerCamelCase			, feature_extractor=lowerCamelCase   )

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




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase   )				->str:



         '''simple docstring'''
         __a  ,      __a					  =     examples
         __a					  =     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   )},
             ]			, )
         __a					  =     audio_classifier(lowerCamelCase			, top_k=1   )
         self.assertEqual(
             lowerCamelCase			, [
                 {'score': ANY(lowerCamelCase   ), 'label': ANY(lowerCamelCase   )},
             ]			, )

         self.run_torchaudio(lowerCamelCase   )




      @require_torchaudio
      def 			__UpperCamelCase				(	self			, lowerCamelCase   )				->Union[str, Any]:



         '''simple docstring'''
         import datasets

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




      @require_torch
      def 			__UpperCamelCase				(	self   )				->Optional[int]:



         '''simple docstring'''
         __a					  =     'anton-l/wav2vec2-random-tiny-classifier'

         __a					  =     pipeline('audio-classification'			, model=lowerCamelCase   )

         __a					  =     np.ones((8000,)   )
         __a					  =     audio_classifier(lowerCamelCase			, top_k=4   )

         __a					  =     [
             {'score': 0.0842, 'label': 'no'},
             {'score': 0.0838, 'label': 'up'},
             {'score': 0.0837, 'label': 'go'},
             {'score': 0.0834, 'label': 'right'},
         ]
         __a					  =     [
             {'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]   )

         __a					  =     {'array': np.ones((8000,)   ), 'sampling_rate': audio_classifier.feature_extractor.sampling_rate}
         __a					  =     audio_classifier(lowerCamelCase			, top_k=4   )
         self.assertIn(nested_simplify(lowerCamelCase			, decimals=4   )			, [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]   )




      @require_torch
      @slow
      def 			__UpperCamelCase				(	self   )				->str:



         '''simple docstring'''
         import datasets

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

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

         __a					  =     np.array(dataset[3]['speech']			, dtype=np.floataa   )
         __a					  =     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 			__UpperCamelCase				(	self   )				->str:



         '''simple docstring'''
         pass







'''simple docstring'''



import copy
import random

from transformers import CLIPTokenizer
class 				__SCREAMING_SNAKE_CASE							(				_lowerCAmelCase  ):




      def __init__(	self			, *lowerCamelCase			, **lowerCamelCase   )				->Union[str, Any]:



         '''simple docstring'''
         super().__init__(*lowerCamelCase			, **lowerCamelCase   )
         __a					  =     {}




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, *lowerCamelCase			, **lowerCamelCase   )				->Dict:



         '''simple docstring'''
         __a					  =     super().add_tokens(lowerCamelCase			, *lowerCamelCase			, **lowerCamelCase   )
         if num_added_tokens == 0:
            raise ValueError(
                F"""The tokenizer already contains the token {placeholder_token}. Please pass a different"""
                ' `placeholder_token` that is not already in the tokenizer.'   )




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, *lowerCamelCase			, lowerCamelCase=1			, **lowerCamelCase   )				->List[str]:



         '''simple docstring'''
         __a					  =     []
         if num_vec_per_token == 1:
            self.try_adding_tokens(lowerCamelCase			, *lowerCamelCase			, **lowerCamelCase   )
            output.append(lowerCamelCase   )
         else:
            __a					  =     []
            for i in range(lowerCamelCase   ):
               __a					  =     placeholder_token + F"""_{i}"""
               self.try_adding_tokens(lowerCamelCase			, *lowerCamelCase			, **lowerCamelCase   )
               output.append(lowerCamelCase   )
        # handle cases where there is a new placeholder token that contains the current placeholder token but is larger
         for token in self.token_map:
            if token in placeholder_token:
               raise ValueError(
                   F"""The tokenizer already has placeholder token {token} that can get confused with"""
                   F""" {placeholder_token}keep placeholder tokens independent"""   )
         __a					  =     output




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase=False			, lowerCamelCase=1.0   )				->int:



         '''simple docstring'''
         if isinstance(lowerCamelCase			, lowerCamelCase   ):
            __a					  =     []
            for i in range(len(lowerCamelCase   )   ):
               output.append(self.replace_placeholder_tokens_in_text(text[i]			, vector_shuffle=lowerCamelCase   )   )
            return output
         for placeholder_token in self.token_map:
            if placeholder_token in text:
               __a					  =     self.token_map[placeholder_token]
               __a					  =     tokens[: 1 + int(len(lowerCamelCase   ) * prop_tokens_to_load   )]
               if vector_shuffle:
                  __a					  =     copy.copy(lowerCamelCase   )
                  random.shuffle(lowerCamelCase   )
               __a					  =     text.replace(lowerCamelCase			, ' '.join(lowerCamelCase   )   )
         return text




      def __call__(	self			, lowerCamelCase			, *lowerCamelCase			, lowerCamelCase=False			, lowerCamelCase=1.0			, **lowerCamelCase   )				->Optional[int]:



         '''simple docstring'''
         return super().__call__(
             self.replace_placeholder_tokens_in_text(
                 lowerCamelCase			, vector_shuffle=lowerCamelCase			, prop_tokens_to_load=lowerCamelCase   )			, *lowerCamelCase			, **lowerCamelCase			, )






      def 			__UpperCamelCase				(	self			, lowerCamelCase			, *lowerCamelCase			, lowerCamelCase=False			, lowerCamelCase=1.0			, **lowerCamelCase   )				->List[Any]:



         '''simple docstring'''
         return super().encode(
             self.replace_placeholder_tokens_in_text(
                 lowerCamelCase			, vector_shuffle=lowerCamelCase			, prop_tokens_to_load=lowerCamelCase   )			, *lowerCamelCase			, **lowerCamelCase			, )