


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


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


class   a__	(						unittest.TestCase    ):

       def 						UpperCAmelCase(   self      :     Optional[int]    ):
            a_    :     Union[str, Any]										=    0

       def 						UpperCAmelCase(   self      :     Tuple    ):
            a_    :     str										=    AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""    )
            self.assertIsInstance(__lowerCamelCase      ,							__lowerCamelCase    )

       def 						UpperCAmelCase(   self      :     Optional[Any]    ):
            a_    :     Optional[int]										=    AutoFeatureExtractor.from_pretrained(__lowerCamelCase    )
            self.assertIsInstance(__lowerCamelCase      ,							__lowerCamelCase    )

       def 						UpperCAmelCase(   self      :     Dict    ):






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

                 # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
                 a_    :     int										=    AutoFeatureExtractor.from_pretrained(__lowerCamelCase    ).to_dict()

                 config_dict.pop("""feature_extractor_type"""    )
                 a_    :     Tuple										=    WavaVecaFeatureExtractor(**__lowerCamelCase    )

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

                 a_    :     Union[str, Any]										=    AutoFeatureExtractor.from_pretrained(__lowerCamelCase    )

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

            self.assertIsInstance(__lowerCamelCase      ,							__lowerCamelCase    )

       def 						UpperCAmelCase(   self      :     Tuple    ):
            a_    :     Optional[int]										=    AutoFeatureExtractor.from_pretrained(__lowerCamelCase    )
            self.assertIsInstance(__lowerCamelCase      ,							__lowerCamelCase    )

       def 						UpperCAmelCase(   self      :     List[Any]    ):






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

       def 						UpperCAmelCase(   self      :     List[Any]    ):






            with self.assertRaisesRegex(
                __lowerCamelCase      ,							R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""    ):
                 a_    :     List[Any]										=    AutoFeatureExtractor.from_pretrained(__lowerCamelCase      ,							revision="""aaaaaa"""    )

       def 						UpperCAmelCase(   self      :     int    ):






            with self.assertRaisesRegex(
                __lowerCamelCase      ,							"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""      ,							):
                 a_    :     int										=    AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""    )

       def 						UpperCAmelCase(   self      :     Optional[int]    ):






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

            a_    :     int										=    AutoFeatureExtractor.from_pretrained(
                """hf-internal-testing/test_dynamic_feature_extractor"""      ,							trust_remote_code=__lowerCamelCase    )
            self.assertEqual(feature_extractor.__class__.__name__      ,							"""NewFeatureExtractor"""    )

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

       def 						UpperCAmelCase(   self      :     Tuple    ):






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

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

            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 						UpperCAmelCase(   self      :     Any    ):


            class   a__	(						lowerCamelCase__    ):
                   lowerCamelCase__:     str							    =     True

            try:
                 AutoConfig.register("""custom"""      ,							__lowerCamelCase    )
                 AutoFeatureExtractor.register(__lowerCamelCase      ,							__lowerCamelCase    )
                 # If remote code is not set, the default is to use local
                 a_    :     Union[str, 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.
                 a_    :     List[str]										=    AutoFeatureExtractor.from_pretrained(
                     """hf-internal-testing/test_dynamic_feature_extractor"""      ,							trust_remote_code=__lowerCamelCase    )
                 self.assertEqual(feature_extractor.__class__.__name__      ,							"""NewFeatureExtractor"""    )
                 self.assertTrue(feature_extractor.is_local    )

                 # If remote is enabled, we load from the Hub
                 a_    :     Any										=    AutoFeatureExtractor.from_pretrained(
                     """hf-internal-testing/test_dynamic_feature_extractor"""      ,							trust_remote_code=__lowerCamelCase    )
                 self.assertEqual(feature_extractor.__class__.__name__      ,							"""NewFeatureExtractor"""    )
                 self.assertTrue(not hasattr(__lowerCamelCase      ,							"""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 dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


__lowerCamelCase        =     logging.get_logger(__name__)



def  _a			(						__UpperCamelCase=None  ,  __UpperCamelCase=None ):
     return field(default_factory=lambda: default  ,  metadata=__UpperCamelCase )


@dataclass
class   a__	:
       lowerCamelCase__:     List[str]							    =     list_field(
           default=[]						,       metadata={
               """help""": (
                   """Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"""
                   """ of all available models"""
               )
           }						,       )

       lowerCamelCase__:     List[int]							    =     list_field(
           default=[8]						,       metadata={"""help""": """List of batch sizes for which memory and time performance will be evaluated"""}    )

       lowerCamelCase__:     List[int]							    =     list_field(
           default=[8, 32, 128, 512]						,       metadata={"""help""": """List of sequence lengths for which memory and time performance will be evaluated"""}						,       )

       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={"""help""": """Whether to benchmark inference of model. Inference can be disabled via --no-inference."""}						,       )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={"""help""": """Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."""}						,       )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={"""help""": """Whether to run on available tpu devices. TPU can be disabled via --no-tpu."""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Use FP16 to accelerate inference."""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Benchmark training of model"""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Verbose memory tracing"""}    )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={"""help""": """Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."""}						,       )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={
               """help""": """Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"""
           }						,       )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Trace memory line by line"""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Save result to a CSV file"""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Save all print statements in a log file"""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Whether to print environment information"""}    )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={
               """help""": (
                   """Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"""
                   """ multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"""
                   """ for debugging / testing and on TPU."""
               )
           }						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""inference_time_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving time results to csv."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""inference_memory_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving memory results to csv."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""train_time_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving time results to csv for training."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""train_memory_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving memory results to csv for training."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""env_info_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving environment information."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""log_{round(time()    )}.csv"""						,       metadata={"""help""": """Log filename used if print statements are saved in log."""}						,       )
       lowerCamelCase__:     int							    =     field(default=3						,       metadata={"""help""": """Times an experiment will be run."""}    )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={
               """help""": (
                   """Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"""
                   """ model weights."""
               )
           }						,       )

       def 						UpperCAmelCase(   self      :     Any    ):
            warnings.warn(
                F'''The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'''
                """ are deprecated in general and it is advised to use external Benchmarking libraries """
                """ to benchmark Transformer models."""      ,							lowerCamelCase_      ,							)

       def 						UpperCAmelCase(   self      :     Union[str, Any]    ):
            return json.dumps(dataclasses.asdict(self    )      ,							indent=2    )

       @property
       def 						UpperCAmelCase(   self      :     List[str]    ):
            if len(self.models    ) <= 0:
                 raise ValueError(
                     """Please make sure you provide at least one model name / model identifier, *e.g.* `--models"""
                     """ bert-base-cased` or `args.models = ['bert-base-cased']."""    )
            return self.models

       @property
       def 						UpperCAmelCase(   self      :     Union[str, Any]    ):
            if not self.multi_process:
                 return False
            elif self.is_tpu:
                 logger.info("""Multiprocessing is currently not possible on TPU."""    )
                 return False
            else:
                 return True



