



'''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 				snake_case (unittest.TestCase   ):
       lowerCAmelCase__  :Tuple						   =					MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
       lowerCAmelCase__  :Tuple						   =					TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Tuple:
           lowercase__		       =						AudioClassificationPipeline(model=UpperCAmelCase_     ,feature_extractor=UpperCAmelCase_      )

           # test with a raw waveform
           lowercase__		       =						np.zeros((34_000,)      )
           lowercase__		       =						np.zeros((14_000,)      )
           return audio_classifier, [audioa, audio]



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							List[str]:
           lowercase__       ,       lowercase__		       =						examples
           lowercase__		       =						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__		       =						audio_classifier(UpperCAmelCase_     ,top_k=1      )
           self.assertEqual(
               UpperCAmelCase_     ,[
                   {"score": ANY(UpperCAmelCase_      ), "label": ANY(UpperCAmelCase_      )},
               ]     ,)

           self.run_torchaudio(UpperCAmelCase_      )



       @require_torchaudio
       def 							_a      (				self     ,UpperCAmelCase_      )  ->							Tuple:
           import datasets

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



       @require_torch
       def 							_a      (				self      )  ->							Dict:
           lowercase__		       =						"anton-l/wav2vec2-random-tiny-classifier"

           lowercase__		       =						pipeline("audio-classification"     ,model=UpperCAmelCase_      )

           lowercase__		       =						np.ones((8_000,)      )
           lowercase__		       =						audio_classifier(UpperCAmelCase_     ,top_k=4      )

           lowercase__		       =						[
               {"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__		       =						[
               {"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__		       =						{"array": np.ones((8_000,)      ), "sampling_rate": audio_classifier.feature_extractor.sampling_rate}
           lowercase__		       =						audio_classifier(UpperCAmelCase_     ,top_k=4      )
           self.assertIn(nested_simplify(UpperCAmelCase_     ,decimals=4      )     ,[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]      )



       @require_torch
       @slow
       def 							_a      (				self      )  ->							Tuple:
           import datasets

           lowercase__		       =						"superb/wav2vec2-base-superb-ks"

           lowercase__		       =						pipeline("audio-classification"     ,model=UpperCAmelCase_      )
           lowercase__		       =						datasets.load_dataset("anton-l/superb_dummy"     ,"ks"     ,split="test"      )

           lowercase__		       =						np.array(dataset[3]["speech"]     ,dtype=np.floataa      )
           lowercase__		       =						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 							_a      (				self      )  ->							Optional[Any]:
           pass









'''simple docstring'''





import os
import time

import numpy as np
import onnxruntime as ort


SCREAMING_SNAKE_CASE__      					=     "1"
SCREAMING_SNAKE_CASE__      					=     "0"
SCREAMING_SNAKE_CASE__      					=     "1"

SCREAMING_SNAKE_CASE__      					=     ort.SessionOptions()
SCREAMING_SNAKE_CASE__      					=     ort.GraphOptimizationLevel.ORT_DISABLE_ALL
print("Create inference session...")
SCREAMING_SNAKE_CASE__      					=     ["TensorrtExecutionProvider", "CUDAExecutionProvider"]
SCREAMING_SNAKE_CASE__      					=     ort.InferenceSession("model.onnx", sess_options=sess_opt, providers=execution_provider)
SCREAMING_SNAKE_CASE__      					=     ort.RunOptions()

SCREAMING_SNAKE_CASE__      					=     128
SCREAMING_SNAKE_CASE__      					=     1
SCREAMING_SNAKE_CASE__      					=     np.ones((batch, sequence), dtype=np.intaa)
SCREAMING_SNAKE_CASE__      					=     np.ones((batch, sequence), dtype=np.intaa)
SCREAMING_SNAKE_CASE__      					=     np.ones((batch, sequence), dtype=np.intaa)

print("Warm up phase...")
sess.run(
    None,
    {
        sess.get_inputs()[0].name: input_ids,
        sess.get_inputs()[1].name: attention_mask,
        sess.get_inputs()[2].name: token_type_ids,
    },
    run_options=run_opt,
)

print("Start inference...")
SCREAMING_SNAKE_CASE__      					=     time.time()
SCREAMING_SNAKE_CASE__      					=     2000
SCREAMING_SNAKE_CASE__      					=     {}
for iter in range(max_iters):
 SCREAMING_SNAKE_CASE__      					=     sess.run(
     None,
     {
         sess.get_inputs()[0].name: input_ids,
         sess.get_inputs()[1].name: attention_mask,
         sess.get_inputs()[2].name: token_type_ids,
     },
     run_options=run_opt,
 )
print("Average Inference Time = {:.3f} ms".format((time.time() - start_time) * 1000 / max_iters))




