



import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


UpperCamelCase_										=					get_tests_dir('''fixtures''')
UpperCamelCase_										=					get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
UpperCamelCase_										=					get_tests_dir('''fixtures/dummy-config.json''')







class 	_snake_case							(			unittest.TestCase      ):






   '''simple docstring'''






   def 	A__  (  self:			Optional[Any]				)     ->	List[str]:
       UpperCAmelCase_			:    Optional[int]   						= 0


   def 	A__  (  self:			Dict				)     ->	Optional[Any]:
       UpperCAmelCase_			:    int   						= AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""				)
       self.assertIsInstance(UpperCamelCase__   ,UpperCamelCase__				)


   def 	A__  (  self:			Any				)     ->	Dict:
       UpperCAmelCase_			:    str   						= AutoFeatureExtractor.from_pretrained(UpperCamelCase__				)
       self.assertIsInstance(UpperCamelCase__   ,UpperCamelCase__				)


   def 	A__  (  self:			Optional[Any]				)     ->	Union[str, Any]:





       with tempfile.TemporaryDirectory() as tmpdirname:
           UpperCAmelCase_			:    Any   						= WavaVecaConfig()

           # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
           UpperCAmelCase_			:    Any   						= AutoFeatureExtractor.from_pretrained(UpperCamelCase__				).to_dict()

           config_dict.pop("""feature_extractor_type"""				)
           UpperCAmelCase_			:    Optional[int]   						= WavaVecaFeatureExtractor(**UpperCamelCase__				)

           # save in new folder
           model_config.save_pretrained(UpperCamelCase__				)
           config.save_pretrained(UpperCamelCase__				)

           UpperCAmelCase_			:    Optional[int]   						= AutoFeatureExtractor.from_pretrained(UpperCamelCase__				)

           # make sure private variable is not incorrectly saved
           UpperCAmelCase_			:    Optional[Any]   						= json.loads(config.to_json_string()				)
           self.assertTrue("""_processor_class""" not in dict_as_saved				)

       self.assertIsInstance(UpperCamelCase__   ,UpperCamelCase__				)


   def 	A__  (  self:			Tuple				)     ->	Optional[int]:
       UpperCAmelCase_			:    Dict   						= AutoFeatureExtractor.from_pretrained(UpperCamelCase__				)
       self.assertIsInstance(UpperCamelCase__   ,UpperCamelCase__				)


   def 	A__  (  self:			List[Any]				)     ->	int:





       with self.assertRaisesRegex(
           UpperCamelCase__   ,"""bert-base is not a local folder and is not a valid model identifier"""				):
           UpperCAmelCase_			:    List[Any]   						= AutoFeatureExtractor.from_pretrained("""bert-base"""				)


   def 	A__  (  self:			Optional[int]				)     ->	Dict:





       with self.assertRaisesRegex(
           UpperCamelCase__   ,R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""				):
           UpperCAmelCase_			:    Optional[int]   						= AutoFeatureExtractor.from_pretrained(UpperCamelCase__   ,revision="""aaaaaa"""				)


   def 	A__  (  self:			Dict				)     ->	Dict:





       with self.assertRaisesRegex(
           UpperCamelCase__   ,"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""   ,):
           UpperCAmelCase_			:    List[str]   						= AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""				)


   def 	A__  (  self:			Optional[int]				)     ->	int:





       with self.assertRaises(UpperCamelCase__				):
           UpperCAmelCase_			:    int   						= AutoFeatureExtractor.from_pretrained(
               """hf-internal-testing/test_dynamic_feature_extractor"""				)
       # If remote code is disabled, we can't load this config.
       with self.assertRaises(UpperCamelCase__				):
           UpperCAmelCase_			:    List[str]   						= AutoFeatureExtractor.from_pretrained(
               """hf-internal-testing/test_dynamic_feature_extractor"""   ,trust_remote_code=UpperCamelCase__				)

       UpperCAmelCase_			:    Dict   						= AutoFeatureExtractor.from_pretrained(
           """hf-internal-testing/test_dynamic_feature_extractor"""   ,trust_remote_code=UpperCamelCase__				)
       self.assertEqual(feature_extractor.__class__.__name__   ,"""NewFeatureExtractor"""				)

       # Test feature extractor can be reloaded.
       with tempfile.TemporaryDirectory() as tmp_dir:
           feature_extractor.save_pretrained(UpperCamelCase__				)
           UpperCAmelCase_			:    Optional[int]   						= AutoFeatureExtractor.from_pretrained(UpperCamelCase__   ,trust_remote_code=UpperCamelCase__				)
       self.assertEqual(reloaded_feature_extractor.__class__.__name__   ,"""NewFeatureExtractor"""				)


   def 	A__  (  self:			Optional[int]				)     ->	Union[str, Any]:





       try:
           AutoConfig.register("""custom"""   ,UpperCamelCase__				)
           AutoFeatureExtractor.register(UpperCamelCase__   ,UpperCamelCase__				)
           # Trying to register something existing in the Transformers library will raise an error
           with self.assertRaises(UpperCamelCase__				):
               AutoFeatureExtractor.register(UpperCamelCase__   ,UpperCamelCase__				)

           # Now that the config is registered, it can be used as any other config with the auto-API
           UpperCAmelCase_			:    Any   						= CustomFeatureExtractor.from_pretrained(UpperCamelCase__				)
           with tempfile.TemporaryDirectory() as tmp_dir:
               feature_extractor.save_pretrained(UpperCamelCase__				)
               UpperCAmelCase_			:    Any   						= AutoFeatureExtractor.from_pretrained(UpperCamelCase__				)
               self.assertIsInstance(UpperCamelCase__   ,UpperCamelCase__				)

       finally:
           if "custom" in CONFIG_MAPPING._extra_content:
               del CONFIG_MAPPING._extra_content["custom"]
           if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
               del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]






   def 	A__  (  self:			Optional[Any]				)     ->	Dict:







       class 	_snake_case							(			UpperCamelCase_      ):






          '''simple docstring'''






          A__	:      List[str]    =		True

       try:
           AutoConfig.register("""custom"""   ,UpperCamelCase__				)
           AutoFeatureExtractor.register(UpperCamelCase__   ,UpperCamelCase__				)
           # If remote code is not set, the default is to use local
           UpperCAmelCase_			:    List[Any]   						= AutoFeatureExtractor.from_pretrained(
               """hf-internal-testing/test_dynamic_feature_extractor"""				)
           self.assertEqual(feature_extractor.__class__.__name__   ,"""NewFeatureExtractor"""				)
           self.assertTrue(feature_extractor.is_local				)

           # If remote code is disabled, we load the local one.
           UpperCAmelCase_			:    int   						= AutoFeatureExtractor.from_pretrained(
               """hf-internal-testing/test_dynamic_feature_extractor"""   ,trust_remote_code=UpperCamelCase__				)
           self.assertEqual(feature_extractor.__class__.__name__   ,"""NewFeatureExtractor"""				)
           self.assertTrue(feature_extractor.is_local				)

           # If remote is enabled, we load from the Hub
           UpperCAmelCase_			:    Dict   						= AutoFeatureExtractor.from_pretrained(
               """hf-internal-testing/test_dynamic_feature_extractor"""   ,trust_remote_code=UpperCamelCase__				)
           self.assertEqual(feature_extractor.__class__.__name__   ,"""NewFeatureExtractor"""				)
           self.assertTrue(not hasattr(UpperCamelCase__   ,"""is_local"""				)				)

       finally:
           if "custom" in CONFIG_MAPPING._extra_content:
               del CONFIG_MAPPING._extra_content["custom"]
           if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
               del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]

import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
					import tensorflow as tf

					from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments





@require_tf
class 					lowercase__						(   unittest.TestCase):


						def        __A       (       self	:				str    ,		UpperCamelCase__	:				int						):





												'''simple docstring'''





												for model_result in results.values():
																		for batch_size, sequence_length in zip(model_result['''bs''']    ,		model_result['''ss''']						):
																								SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							model_result['''result'''][batch_size][sequence_length]
																								self.assertIsNotNone(UpperCamelCase__						)


						def        __A       (       self	:				Optional[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    List[Any]							=							'''sshleifer/tiny-gpt2'''
												SCREAMING_SNAKE_CASE							:    List[Any]							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		eager_mode=UpperCamelCase__    ,		multi_process=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    str							=							TensorFlowBenchmark(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    List[Any]							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result						)
												self.check_results_dict_not_empty(results.memory_inference_result						)


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    str							=							'''sgugger/tiny-distilbert-classification'''
												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		multi_process=UpperCamelCase__    ,		only_pretrain_model=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    List[str]							=							TensorFlowBenchmark(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    Optional[Any]							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result						)
												self.check_results_dict_not_empty(results.memory_inference_result						)


						def        __A       (       self	:				Any						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							'''sshleifer/tiny-gpt2'''
												SCREAMING_SNAKE_CASE							:    int							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		multi_process=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							TensorFlowBenchmark(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    int							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result						)
												self.check_results_dict_not_empty(results.memory_inference_result						)


						def        __A       (       self	:				Optional[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Optional[int]							=							'''sshleifer/tiny-gpt2'''
												SCREAMING_SNAKE_CASE							:    int							=							AutoConfig.from_pretrained(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    Optional[int]							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		eager_mode=UpperCamelCase__    ,		multi_process=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    str							=							TensorFlowBenchmark(UpperCamelCase__    ,		[config]						)
												SCREAMING_SNAKE_CASE							:    Optional[int]							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result						)
												self.check_results_dict_not_empty(results.memory_inference_result						)


						def        __A       (       self	:				int						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Dict							=							'''sshleifer/tiny-gpt2'''
												SCREAMING_SNAKE_CASE							:    Optional[int]							=							AutoConfig.from_pretrained(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    Optional[Any]							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		multi_process=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    List[str]							=							TensorFlowBenchmark(UpperCamelCase__    ,		[config]						)
												SCREAMING_SNAKE_CASE							:    int							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result						)
												self.check_results_dict_not_empty(results.memory_inference_result						)


						def        __A       (       self	:				List[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    str							=							'''sshleifer/tiny-gpt2'''
												SCREAMING_SNAKE_CASE							:    int							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		multi_process=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    Optional[int]							=							TensorFlowBenchmark(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    Tuple							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result						)
												self.check_results_dict_not_empty(results.memory_train_result						)


						def        __A       (       self	:				Optional[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    List[str]							=							'''sshleifer/tiny-gpt2'''
												SCREAMING_SNAKE_CASE							:    int							=							AutoConfig.from_pretrained(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    Tuple							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		multi_process=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    Dict							=							TensorFlowBenchmark(UpperCamelCase__    ,		[config]						)
												SCREAMING_SNAKE_CASE							:    str							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result						)
												self.check_results_dict_not_empty(results.memory_train_result						)


						def        __A       (       self	:				Optional[int]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    List[str]							=							'''patrickvonplaten/t5-tiny-random'''
												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							AutoConfig.from_pretrained(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		multi_process=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    Dict							=							TensorFlowBenchmark(UpperCamelCase__    ,		configs=[config]						)
												SCREAMING_SNAKE_CASE							:    Dict							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result						)
												self.check_results_dict_not_empty(results.memory_inference_result						)


						@unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('''GPU'''						)						) == 0    ,		'''Cannot do xla on CPU.'''						)
						def        __A       (       self	:				Optional[int]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Optional[Any]							=							'''sshleifer/tiny-gpt2'''
												SCREAMING_SNAKE_CASE							:    Tuple							=							TensorFlowBenchmarkArguments(
												    models=[MODEL_ID]    ,		training=UpperCamelCase__    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		use_xla=UpperCamelCase__    ,		multi_process=UpperCamelCase__    ,		)
												SCREAMING_SNAKE_CASE							:    Any							=							TensorFlowBenchmark(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    List[Any]							=							benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result						)
												self.check_results_dict_not_empty(results.memory_inference_result						)


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Optional[int]							=							'''sshleifer/tiny-gpt2'''
												with tempfile.TemporaryDirectory() as tmp_dir:
																		SCREAMING_SNAKE_CASE							:    Tuple							=							TensorFlowBenchmarkArguments(
																		    models=[MODEL_ID]    ,		inference=UpperCamelCase__    ,		save_to_csv=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		inference_time_csv_file=os.path.join(UpperCamelCase__    ,		'''inf_time.csv'''						)    ,		inference_memory_csv_file=os.path.join(UpperCamelCase__    ,		'''inf_mem.csv'''						)    ,		env_info_csv_file=os.path.join(UpperCamelCase__    ,		'''env.csv'''						)    ,		multi_process=UpperCamelCase__    ,		)
																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							TensorFlowBenchmark(UpperCamelCase__						)
																		benchmark.run()
																		self.assertTrue(Path(os.path.join(UpperCamelCase__    ,		'''inf_time.csv'''						)						).exists()						)
																		self.assertTrue(Path(os.path.join(UpperCamelCase__    ,		'''inf_mem.csv'''						)						).exists()						)
																		self.assertTrue(Path(os.path.join(UpperCamelCase__    ,		'''env.csv'''						)						).exists()						)



						def        __A       (       self	:				int						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Any							=							'''sshleifer/tiny-gpt2'''

												def _check_summary_is_not_empty(UpperCamelCase__	:				Dict						):
																		self.assertTrue(hasattr(UpperCamelCase__    ,		'''sequential'''						)						)
																		self.assertTrue(hasattr(UpperCamelCase__    ,		'''cumulative'''						)						)
																		self.assertTrue(hasattr(UpperCamelCase__    ,		'''current'''						)						)
																		self.assertTrue(hasattr(UpperCamelCase__    ,		'''total'''						)						)

												with tempfile.TemporaryDirectory() as tmp_dir:
																		SCREAMING_SNAKE_CASE							:    List[str]							=							TensorFlowBenchmarkArguments(
																		    models=[MODEL_ID]    ,		inference=UpperCamelCase__    ,		sequence_lengths=[8]    ,		batch_sizes=[1]    ,		log_filename=os.path.join(UpperCamelCase__    ,		'''log.txt'''						)    ,		log_print=UpperCamelCase__    ,		trace_memory_line_by_line=UpperCamelCase__    ,		eager_mode=UpperCamelCase__    ,		multi_process=UpperCamelCase__    ,		)
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							TensorFlowBenchmark(UpperCamelCase__						)
																		SCREAMING_SNAKE_CASE							:    Dict							=							benchmark.run()
																		_check_summary_is_not_empty(result.inference_summary						)
																		self.assertTrue(Path(os.path.join(UpperCamelCase__    ,		'''log.txt'''						)						).exists()						)





