

import copy
import os
from typing import Union

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


UpperCAmelCase__ :     Union[str, Any]				    =    logging.get_logger(__name__)

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







class        a__       (   UpperCAmelCase       ):







  """simple docstring"""




  UpperCAmelCase__      : Union[str, Any]			       ="""git_vision_model"""


  def __init__(			self    : Optional[int]				,				UpperCAmelCase__    : Dict=7_6_8				,				UpperCAmelCase__    : int=3_0_7_2				,				UpperCAmelCase__    : List[str]=1_2				,				UpperCAmelCase__    : List[Any]=1_2				,				UpperCAmelCase__    : Tuple=3				,				UpperCAmelCase__    : Dict=2_2_4				,				UpperCAmelCase__    : int=1_6				,				UpperCAmelCase__    : List[str]="quick_gelu"				,				UpperCAmelCase__    : Union[str, Any]=1e-5				,				UpperCAmelCase__    : str=0.0				,				UpperCAmelCase__    : Union[str, Any]=0.02				,				**UpperCAmelCase__    : Tuple				,				)					->Dict:
        """simple docstring"""







        super().__init__(**UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      int       =   hidden_size
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   intermediate_size
        SCREAMING_SNAKE_CASE :      Any       =   num_hidden_layers
        SCREAMING_SNAKE_CASE :      List[Any]       =   num_attention_heads
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   num_channels
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   patch_size
        SCREAMING_SNAKE_CASE :      Any       =   image_size
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   initializer_range
        SCREAMING_SNAKE_CASE :      Dict       =   attention_dropout
        SCREAMING_SNAKE_CASE :      Dict       =   layer_norm_eps
        SCREAMING_SNAKE_CASE :      Any       =   hidden_act




  @classmethod
  def  _lowercase      (			cls    : Tuple				,				UpperCAmelCase__    : Union[str, os.PathLike]				,				**UpperCAmelCase__    : Any		)					->"PretrainedConfig":
        """simple docstring"""







        cls._set_token_in_kwargs(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Tuple       =   cls.get_config_dict(UpperCAmelCase__				,				**UpperCAmelCase__		)

        # get the vision config dict if we are loading from GITConfig
        if config_dict.get("""model_type"""		) == "git":
              SCREAMING_SNAKE_CASE :      Optional[int]       =   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        a__       (   UpperCAmelCase       ):







  """simple docstring"""




  UpperCAmelCase__      : Optional[int]			       ="""git"""


  def __init__(			self    : Optional[Any]				,				UpperCAmelCase__    : Optional[int]=None				,				UpperCAmelCase__    : str=3_0_5_2_2				,				UpperCAmelCase__    : Optional[int]=7_6_8				,				UpperCAmelCase__    : Union[str, Any]=6				,				UpperCAmelCase__    : List[str]=1_2				,				UpperCAmelCase__    : Tuple=3_0_7_2				,				UpperCAmelCase__    : int="gelu"				,				UpperCAmelCase__    : List[str]=0.1				,				UpperCAmelCase__    : str=0.1				,				UpperCAmelCase__    : int=1_0_2_4				,				UpperCAmelCase__    : List[str]=0.02				,				UpperCAmelCase__    : Tuple=1e-12				,				UpperCAmelCase__    : Optional[int]=0				,				UpperCAmelCase__    : str="absolute"				,				UpperCAmelCase__    : Optional[Any]=True				,				UpperCAmelCase__    : str=False				,				UpperCAmelCase__    : Optional[int]=1_0_1				,				UpperCAmelCase__    : Optional[Any]=1_0_2				,				UpperCAmelCase__    : Union[str, Any]=None				,				**UpperCAmelCase__    : List[Any]				,				)					->List[Any]:
        """simple docstring"""







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

        if vision_config is None:
              SCREAMING_SNAKE_CASE :      Dict       =   {}
              logger.info("""vision_config is None. initializing the GitVisionConfig with default values."""		)

        SCREAMING_SNAKE_CASE :      int       =   GitVisionConfig(**UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   vocab_size
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   hidden_size
        SCREAMING_SNAKE_CASE :      Optional[int]       =   num_hidden_layers
        SCREAMING_SNAKE_CASE :      Optional[int]       =   num_attention_heads
        SCREAMING_SNAKE_CASE :      Any       =   hidden_act
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   intermediate_size
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   hidden_dropout_prob
        SCREAMING_SNAKE_CASE :      int       =   attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE :      List[Any]       =   max_position_embeddings
        SCREAMING_SNAKE_CASE :      Optional[int]       =   initializer_range
        SCREAMING_SNAKE_CASE :      List[Any]       =   layer_norm_eps
        SCREAMING_SNAKE_CASE :      List[str]       =   position_embedding_type
        SCREAMING_SNAKE_CASE :      int       =   use_cache
        SCREAMING_SNAKE_CASE :      str       =   tie_word_embeddings
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   num_image_with_embedding

        SCREAMING_SNAKE_CASE :      List[Any]       =   bos_token_id
        SCREAMING_SNAKE_CASE :      List[str]       =   eos_token_id




  def  _lowercase      (			self    : Optional[int]		)					->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   copy.deepcopy(self.__dict__		)
        SCREAMING_SNAKE_CASE :      str       =   self.vision_config.to_dict()
        SCREAMING_SNAKE_CASE :      str       =   self.__class__.model_type
        return output







import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


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

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


UpperCAmelCase__ :     int				    =    get_tests_dir("""fixtures""")







class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  def  _lowercase      (			self    : Dict		)					->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   mock.Mock()
        SCREAMING_SNAKE_CASE :      Optional[int]       =   5_0_0
        SCREAMING_SNAKE_CASE :      List[str]       =   {}
        SCREAMING_SNAKE_CASE :      List[Any]       =   HTTPError
        SCREAMING_SNAKE_CASE :      int       =   {}

        # Download this model to make sure it's in the cache.
        SCREAMING_SNAKE_CASE :      List[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2"""		)
        # Under the mock environment we get a 500 error when trying to reach the model.
        with mock.patch("""requests.Session.request"""				,				return_value=UpperCAmelCase__		) as mock_head:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2"""		)
              # This check we did call the fake head request
              mock_head.assert_called()




  def  _lowercase      (			self    : Optional[Any]		)					->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      str       =   WavaVecaFeatureExtractor.from_pretrained(
            """https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"""		)







@is_staging_test
class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  @classmethod
  def  _lowercase      (			cls    : List[str]		)					->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      int       =   TOKEN
        HfFolder.save_token(UpperCAmelCase__		)


  @classmethod
  def  _lowercase      (			cls    : List[str]		)					->Optional[int]:
        """simple docstring"""







        try:
              delete_repo(token=cls._token				,				repo_id="""test-feature-extractor"""		)
        except HTTPError:
              pass

        try:
              delete_repo(token=cls._token				,				repo_id="""valid_org/test-feature-extractor-org"""		)
        except HTTPError:
              pass

        try:
              delete_repo(token=cls._token				,				repo_id="""test-dynamic-feature-extractor"""		)
        except HTTPError:
              pass


  def  _lowercase      (			self    : int		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      int       =   WavaVecaFeatureExtractor.from_pretrained(UpperCAmelCase__		)
        feature_extractor.push_to_hub("""test-feature-extractor"""				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      Any       =   WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)

        # Reset repo
        delete_repo(token=self._token				,				repo_id="""test-feature-extractor"""		)

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
              feature_extractor.save_pretrained(
                  UpperCAmelCase__				,				repo_id="""test-feature-extractor"""				,				push_to_hub=UpperCAmelCase__				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      List[str]       =   WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)


  def  _lowercase      (			self    : List[Any]		)					->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[str]       =   WavaVecaFeatureExtractor.from_pretrained(UpperCAmelCase__		)
        feature_extractor.push_to_hub("""valid_org/test-feature-extractor"""				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor"""		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)

        # Reset repo
        delete_repo(token=self._token				,				repo_id="""valid_org/test-feature-extractor"""		)

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
              feature_extractor.save_pretrained(
                  UpperCAmelCase__				,				repo_id="""valid_org/test-feature-extractor-org"""				,				push_to_hub=UpperCAmelCase__				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      List[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor-org"""		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)




  def  _lowercase      (			self    : Optional[Any]		)					->Optional[int]:
        """simple docstring"""







        CustomFeatureExtractor.register_for_auto_class()
        SCREAMING_SNAKE_CASE :      Any       =   CustomFeatureExtractor.from_pretrained(UpperCAmelCase__		)

        feature_extractor.push_to_hub("""test-dynamic-feature-extractor"""				,				use_auth_token=self._token		)

        # This has added the proper auto_map field to the config
        self.assertDictEqual(
            feature_extractor.auto_map				,				{"""AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor"""}				,				)

        SCREAMING_SNAKE_CASE :      Any       =   AutoFeatureExtractor.from_pretrained(
            f"{USER}/test-dynamic-feature-extractor"				,				trust_remote_code=UpperCAmelCase__		)
        # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
        self.assertEqual(new_feature_extractor.__class__.__name__				,				"""CustomFeatureExtractor"""		)




