



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 					_A (			unittest.TestCase					):
       UpperCamelCase__						:					Any		      =		MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
       UpperCamelCase__						:					Optional[int]		      =		TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING



       def 	_lowerCamelCase    (	self							:  Any  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]  ,	__SCREAMING_SNAKE_CASE							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           __a		 =       AudioClassificationPipeline(model=__SCREAMING_SNAKE_CASE  ,	feature_extractor=__SCREAMING_SNAKE_CASE)

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



       def 	_lowerCamelCase    (	self							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]  ,	__SCREAMING_SNAKE_CASE							:  List[Any]):


           '''simple docstring'''

           __a ,     __a		 =       examples
           __a		 =       audio_classifier(__SCREAMING_SNAKE_CASE)
           # by default a model is initialized with num_labels=2
           self.assertEqual(
               __SCREAMING_SNAKE_CASE  ,	[
                   {'''score''': ANY(__SCREAMING_SNAKE_CASE), '''label''': ANY(__SCREAMING_SNAKE_CASE)},
                   {'''score''': ANY(__SCREAMING_SNAKE_CASE), '''label''': ANY(__SCREAMING_SNAKE_CASE)},
               ]  ,	)
           __a		 =       audio_classifier(__SCREAMING_SNAKE_CASE  ,	top_k=1)
           self.assertEqual(
               __SCREAMING_SNAKE_CASE  ,	[
                   {'''score''': ANY(__SCREAMING_SNAKE_CASE), '''label''': ANY(__SCREAMING_SNAKE_CASE)},
               ]  ,	)

           self.run_torchaudio(__SCREAMING_SNAKE_CASE)



       @require_torchaudio
       def 	_lowerCamelCase    (	self							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  List[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(__SCREAMING_SNAKE_CASE)
           self.assertEqual(
               __SCREAMING_SNAKE_CASE  ,	[
                   {'''score''': ANY(__SCREAMING_SNAKE_CASE), '''label''': ANY(__SCREAMING_SNAKE_CASE)},
                   {'''score''': ANY(__SCREAMING_SNAKE_CASE), '''label''': ANY(__SCREAMING_SNAKE_CASE)},
               ]  ,	)



       @require_torch
       def 	_lowerCamelCase    (	self							:  List[str]):


           '''simple docstring'''

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

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

           __a		 =       np.ones((8_000,))
           __a		 =       audio_classifier(__SCREAMING_SNAKE_CASE  ,	top_k=4)

           __a		 =       [
               {'''score''': 0.08_42, '''label''': '''no'''},
               {'''score''': 0.08_38, '''label''': '''up'''},
               {'''score''': 0.08_37, '''label''': '''go'''},
               {'''score''': 0.08_34, '''label''': '''right'''},
           ]
           __a		 =       [
               {'''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(__SCREAMING_SNAKE_CASE  ,	decimals=4)  ,	[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2])

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



       @require_torch
       @slow
       def 	_lowerCamelCase    (	self							:  Optional[int]):


           '''simple docstring'''

           import datasets

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

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

           __a		 =       np.array(dataset[3]['''speech''']  ,	dtype=np.floataa)
           __a		 =       audio_classifier(__SCREAMING_SNAKE_CASE  ,	top_k=4)
           self.assertEqual(
               nested_simplify(__SCREAMING_SNAKE_CASE  ,	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 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           pass










# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


__snake_case		:Union[str, Any]   	=  Path(__file__).resolve().parents[3] / '''src'''
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

__snake_case		:str   	=  {'''base''': '''patrickvonplaten/wav2vec2_tiny_random''', '''robust''': '''patrickvonplaten/wav2vec2_tiny_random_robust'''}

__snake_case		:List[Any]   	=  '''zero2'''
__snake_case		:Optional[Any]   	=  '''zero3'''
__snake_case		:str   	=  [ZEROa, ZEROa]





def   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase       ):
    # customize the test name generator function as we want both params to appear in the sub-test
    # name, as by default it shows only the first param
    __a		 =       parameterized.to_safe_name('''_'''.join(str(_UpperCAmelCase       ) for x in param.args       )       )
    return f'{func.__name__}_{param_based_name}'


# Cartesian-product of zero stages with models to test
__snake_case		:List[Any]   	=  list(itertools.product(stages, models.keys()))

@slow
@require_deepspeed
@require_torch_gpu
class 					_A (			__UpperCAmelCase					):



       @parameterized.expand(__SCREAMING_SNAKE_CASE  ,	name_func=__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]  ,	__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           self.run_and_check(
               stage=__SCREAMING_SNAKE_CASE  ,	model=__SCREAMING_SNAKE_CASE  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)



       @require_torch_multi_gpu
       @parameterized.expand(__SCREAMING_SNAKE_CASE  ,	name_func=__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]  ,	__SCREAMING_SNAKE_CASE							:  List[Any]):


           '''simple docstring'''

           self.run_and_check(
               stage=__SCREAMING_SNAKE_CASE  ,	model=__SCREAMING_SNAKE_CASE  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)



       @parameterized.expand(__SCREAMING_SNAKE_CASE  ,	name_func=__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]  ,	__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           self.run_and_check(
               stage=__SCREAMING_SNAKE_CASE  ,	model=__SCREAMING_SNAKE_CASE  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)



       @require_torch_multi_gpu
       @parameterized.expand(__SCREAMING_SNAKE_CASE  ,	name_func=__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]  ,	__SCREAMING_SNAKE_CASE							:  List[Any]):


           '''simple docstring'''

           self.run_and_check(
               stage=__SCREAMING_SNAKE_CASE  ,	model=__SCREAMING_SNAKE_CASE  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)



       def 	_lowerCamelCase    (	self							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  List[str]):


           '''simple docstring'''

           pass



       def 	_lowerCamelCase    (	self							:  Any  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  int = 10  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	):


           '''simple docstring'''

           __a		 =       models[model]

           __a		 =       self.run_trainer(
               stage=__SCREAMING_SNAKE_CASE  ,	model_name=__SCREAMING_SNAKE_CASE  ,	eval_steps=__SCREAMING_SNAKE_CASE  ,	num_train_epochs=1  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)

           self.do_checks(__SCREAMING_SNAKE_CASE)

           return output_dir



       def 	_lowerCamelCase    (	self							:  List[str]  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  int = 10  ,	__SCREAMING_SNAKE_CASE							:  int = 1  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	):


           '''simple docstring'''

           __a		 =       self.get_auto_remove_tmp_dir('''./xxx'''  ,	after=__SCREAMING_SNAKE_CASE)
           __a		 =       F'\n            --model_name_or_path {model_name}\n            --dataset_name hf-internal-testing/librispeech_asr_dummy\n            --dataset_config_name clean\n            --train_split_name validation\n            --validation_split_name validation\n            --output_dir {output_dir}\n            --num_train_epochs {str(__SCREAMING_SNAKE_CASE)}\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 2\n            --evaluation_strategy steps\n            --learning_rate 5e-4\n            --warmup_steps 8\n            --orthography timit\n            --preprocessing_num_workers 1\n            --group_by_length\n            --freeze_feature_extractor\n            --report_to none\n            --save_steps 0\n            --eval_steps {eval_steps}\n            --report_to none\n        '.split()

           if fpaa:
               args.extend(['''--fp16'''])

           # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
           # hence the separate config files
           __a		 =       F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split()
           __a		 =       [F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py']
           __a		 =       self.get_launcher(__SCREAMING_SNAKE_CASE)

           __a		 =       launcher + script + args + ds_args
           # keep for quick debug
           # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
           execute_subprocess_async(__SCREAMING_SNAKE_CASE  ,	env=self.get_env())

           return output_dir





       def 	_lowerCamelCase    (	self							:  int  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=False):


           '''simple docstring'''

           __a		 =       min(2  ,	get_gpu_count()) if distributed else 1
           return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()





