




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	:		int							       =   get_tests_dir("""fixtures""")
_lowerCamelCase	:		List[str]							       =   get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
_lowerCamelCase	:		Tuple							       =   get_tests_dir("""fixtures/dummy-config.json""")


class 				UpperCamelCase_    ( unittest.TestCase     ):

    '''simple docstring'''






    def        SCREAMING_SNAKE_CASE							(			self      :	List[str])						->Tuple:





           '''simple docstring'''

           A__       =    0


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





           '''simple docstring'''

           A__       =    AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h''')
           self.assertIsInstance(UpperCAmelCase__					, UpperCAmelCase__)


    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[Any])						->Optional[int]:





           '''simple docstring'''

           A__       =    AutoFeatureExtractor.from_pretrained(UpperCAmelCase__)
           self.assertIsInstance(UpperCAmelCase__					, UpperCAmelCase__)


    def        SCREAMING_SNAKE_CASE							(			self      :	Tuple)						->List[Any]:





           '''simple docstring'''

           with tempfile.TemporaryDirectory() as tmpdirname:
                  A__       =    WavaVecaConfig()

                  # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
                  A__       =    AutoFeatureExtractor.from_pretrained(UpperCAmelCase__).to_dict()

                  config_dict.pop('''feature_extractor_type''')
                  A__       =    WavaVecaFeatureExtractor(**UpperCAmelCase__)

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

                  A__       =    AutoFeatureExtractor.from_pretrained(UpperCAmelCase__)

                  # make sure private variable is not incorrectly saved
                  A__       =    json.loads(config.to_json_string())
                  self.assertTrue('''_processor_class''' not in dict_as_saved)

           self.assertIsInstance(UpperCAmelCase__					, UpperCAmelCase__)


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





           '''simple docstring'''

           A__       =    AutoFeatureExtractor.from_pretrained(UpperCAmelCase__)
           self.assertIsInstance(UpperCAmelCase__					, UpperCAmelCase__)


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





           '''simple docstring'''

           with self.assertRaisesRegex(
               UpperCAmelCase__					, '''bert-base is not a local folder and is not a valid model identifier'''):
                  A__       =    AutoFeatureExtractor.from_pretrained('''bert-base''')


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





           '''simple docstring'''

           with self.assertRaisesRegex(
               UpperCAmelCase__					, R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''):
                  A__       =    AutoFeatureExtractor.from_pretrained(UpperCAmelCase__					, revision='''aaaaaa''')


    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[Any])						->Optional[int]:





           '''simple docstring'''

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


    def        SCREAMING_SNAKE_CASE							(			self      :	List[str])						->int:





           '''simple docstring'''

           with self.assertRaises(UpperCAmelCase__):
                  A__       =    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__):
                  A__       =    AutoFeatureExtractor.from_pretrained(
                      '''hf-internal-testing/test_dynamic_feature_extractor'''					, trust_remote_code=UpperCAmelCase__)

           A__       =    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__)
                  A__       =    AutoFeatureExtractor.from_pretrained(UpperCAmelCase__					, trust_remote_code=UpperCAmelCase__)
           self.assertEqual(reloaded_feature_extractor.__class__.__name__					, '''NewFeatureExtractor''')


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





           '''simple docstring'''

           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
                  A__       =    CustomFeatureExtractor.from_pretrained(UpperCAmelCase__)
                  with tempfile.TemporaryDirectory() as tmp_dir:
                         feature_extractor.save_pretrained(UpperCAmelCase__)
                         A__       =    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        SCREAMING_SNAKE_CASE							(			self      :	Optional[int])						->Dict:





           '''simple docstring'''

           class 				UpperCamelCase_    ( UpperCAmelCase__     ):

               '''simple docstring'''






               UpperCAmelCase__							  =      True

           try:
                  AutoConfig.register('''custom'''					, UpperCAmelCase__)
                  AutoFeatureExtractor.register(UpperCAmelCase__					, UpperCAmelCase__)
                  # If remote code is not set, the default is to use local
                  A__       =    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__       =    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
                  A__       =    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 copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCamelCase	:		Tuple							       =   logging.get_logger(__name__)

_lowerCamelCase	:		str							       =   {
    """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""",
}


class 				UpperCamelCase_    ( UpperCAmelCase__     ):

    '''simple docstring'''






    UpperCAmelCase__							  =      '''git_vision_model'''


    def __init__(			self      :	Any					, UpperCAmelCase__      :	Any=768					, UpperCAmelCase__      :	int=3_072					, UpperCAmelCase__      :	List[str]=12					, UpperCAmelCase__      :	Dict=12					, UpperCAmelCase__      :	Optional[int]=3					, UpperCAmelCase__      :	List[Any]=224					, UpperCAmelCase__      :	Union[str, Any]=16					, UpperCAmelCase__      :	Union[str, Any]="quick_gelu"					, UpperCAmelCase__      :	Dict=1e-5					, UpperCAmelCase__      :	Union[str, Any]=0.0					, UpperCAmelCase__      :	Any=0.02					, **UpperCAmelCase__      :	Any					, )						->Optional[int]:





           '''simple docstring'''

           super().__init__(**UpperCAmelCase__)

           A__       =    hidden_size
           A__       =    intermediate_size
           A__       =    num_hidden_layers
           A__       =    num_attention_heads
           A__       =    num_channels
           A__       =    patch_size
           A__       =    image_size
           A__       =    initializer_range
           A__       =    attention_dropout
           A__       =    layer_norm_eps
           A__       =    hidden_act





    @classmethod
    def        SCREAMING_SNAKE_CASE							(			cls      :	Any					, UpperCAmelCase__      :	Union[str, os.PathLike]					, **UpperCAmelCase__      :	int)						->"PretrainedConfig":





           '''simple docstring'''

           cls._set_token_in_kwargs(UpperCAmelCase__)

           A__ ,							A__       =    cls.get_config_dict(UpperCAmelCase__					, **UpperCAmelCase__)

           # get the vision config dict if we are loading from GITConfig
           if config_dict.get('''model_type''') == "git":
                  A__       =    config_dict['''vision_config''']

           if "model_type" in config_dict and hasattr(cls					, '''model_type''') and config_dict["model_type"] != cls.model_type:
                  logger.warning(
                      f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
                      f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""")

           return cls.from_dict(UpperCAmelCase__					, **UpperCAmelCase__)


class 				UpperCamelCase_    ( UpperCAmelCase__     ):

    '''simple docstring'''






    UpperCAmelCase__							  =      '''git'''


    def __init__(			self      :	Dict					, UpperCAmelCase__      :	Dict=None					, UpperCAmelCase__      :	int=30_522					, UpperCAmelCase__      :	Optional[int]=768					, UpperCAmelCase__      :	Dict=6					, UpperCAmelCase__      :	int=12					, UpperCAmelCase__      :	List[str]=3_072					, UpperCAmelCase__      :	str="gelu"					, UpperCAmelCase__      :	int=0.1					, UpperCAmelCase__      :	Union[str, Any]=0.1					, UpperCAmelCase__      :	List[Any]=1_024					, UpperCAmelCase__      :	List[str]=0.02					, UpperCAmelCase__      :	Any=1e-12					, UpperCAmelCase__      :	Union[str, Any]=0					, UpperCAmelCase__      :	List[Any]="absolute"					, UpperCAmelCase__      :	int=True					, UpperCAmelCase__      :	Any=False					, UpperCAmelCase__      :	int=101					, UpperCAmelCase__      :	Tuple=102					, UpperCAmelCase__      :	Dict=None					, **UpperCAmelCase__      :	List[str]					, )						->Any:





           '''simple docstring'''

           super().__init__(bos_token_id=UpperCAmelCase__					, eos_token_id=UpperCAmelCase__					, pad_token_id=UpperCAmelCase__					, **UpperCAmelCase__)

           if vision_config is None:
                  A__       =    {}
                  logger.info('''vision_config is None. initializing the GitVisionConfig with default values.''')

           A__       =    GitVisionConfig(**UpperCAmelCase__)
           A__       =    vocab_size
           A__       =    hidden_size
           A__       =    num_hidden_layers
           A__       =    num_attention_heads
           A__       =    hidden_act
           A__       =    intermediate_size
           A__       =    hidden_dropout_prob
           A__       =    attention_probs_dropout_prob
           A__       =    max_position_embeddings
           A__       =    initializer_range
           A__       =    layer_norm_eps
           A__       =    position_embedding_type
           A__       =    use_cache
           A__       =    tie_word_embeddings
           A__       =    num_image_with_embedding

           A__       =    bos_token_id
           A__       =    eos_token_id





    def        SCREAMING_SNAKE_CASE							(			self      :	Any)						->List[Any]:





           '''simple docstring'''

           A__       =    copy.deepcopy(self.__dict__)
           A__       =    self.vision_config.to_dict()
           A__       =    self.__class__.model_type
           return output


