

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

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
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


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





class 				__lowerCAmelCase  (      unittest.TestCase							):




  def 						A__  (       self      )						->				str:
        '''simple docstring'''






        _lowercase			 =0




  def 						A__  (       self      )						->				Dict:
        '''simple docstring'''






        self.assertIsNotNone(transformers.models.auto.__spec__      )
        self.assertIsNotNone(importlib.util.find_spec('transformers.models.auto'      )      )




  def 						A__  (       self      )						->				str:
        '''simple docstring'''






        _lowercase			 =AutoConfig.from_pretrained('bert-base-uncased'      )
        self.assertIsInstance(lowerCAmelCase							,     lowerCAmelCase      )




  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        _lowercase			 =AutoConfig.from_pretrained(lowerCAmelCase      )
        self.assertIsInstance(lowerCAmelCase							,     lowerCAmelCase      )




  def 						A__  (       self      )						->				Optional[Any]:
        '''simple docstring'''






        _lowercase			 =AutoConfig.from_pretrained(lowerCAmelCase      )
        self.assertIsInstance(lowerCAmelCase							,     lowerCAmelCase      )




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






        _lowercase			 =AutoConfig.for_model('roberta'      )
        self.assertIsInstance(lowerCAmelCase							,     lowerCAmelCase      )




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






        with tempfile.TemporaryDirectory() as tmp_dir:
              # This model name contains bert and roberta, but roberta ends up being picked.
              _lowercase			 =os.path.join(lowerCAmelCase							,     'fake-roberta'      )
              os.makedirs(lowerCAmelCase							,     exist_ok=lowerCAmelCase      )
              with open(os.path.join(lowerCAmelCase							,     'config.json'      )							,     'w'      ) as f:
                    f.write(json.dumps({}      )      )
              _lowercase			 =AutoConfig.from_pretrained(lowerCAmelCase      )
              self.assertEqual(type(lowerCAmelCase      )							,     lowerCAmelCase      )




  def 						A__  (       self      )						->				int:
        '''simple docstring'''






        try:
              AutoConfig.register('custom'							,     lowerCAmelCase      )
              # Wrong model type will raise an error
              with self.assertRaises(lowerCAmelCase      ):
                    AutoConfig.register('model'							,     lowerCAmelCase      )
              # Trying to register something existing in the Transformers library will raise an error
              with self.assertRaises(lowerCAmelCase      ):
                    AutoConfig.register('bert'							,     lowerCAmelCase      )

              # Now that the config is registered, it can be used as any other config with the auto-API
              _lowercase			 =CustomConfig()
              with tempfile.TemporaryDirectory() as tmp_dir:
                    config.save_pretrained(lowerCAmelCase      )
                    _lowercase			 =AutoConfig.from_pretrained(lowerCAmelCase      )
                    self.assertIsInstance(lowerCAmelCase							,     lowerCAmelCase      )

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




  def 						A__  (       self      )						->				List[str]:
        '''simple docstring'''






        with self.assertRaisesRegex(
            lowerCAmelCase							,     'bert-base is not a local folder and is not a valid model identifier'      ):
              _lowercase			 =AutoConfig.from_pretrained('bert-base'      )




  def 						A__  (       self      )						->				List[Any]:
        '''simple docstring'''






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




  def 						A__  (       self      )						->				Tuple:
        '''simple docstring'''






        with self.assertRaisesRegex(
            lowerCAmelCase							,     'hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.'							,     ):
              _lowercase			 =AutoConfig.from_pretrained('hf-internal-testing/no-config-test-repo'      )




  def 						A__  (       self      )						->				Optional[Any]:
        '''simple docstring'''






        with self.assertRaises(lowerCAmelCase      ):
              _lowercase			 =AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'      )
        # If remote code is disabled, we can't load this config.
        with self.assertRaises(lowerCAmelCase      ):
              _lowercase			 =AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'							,     trust_remote_code=lowerCAmelCase      )

        _lowercase			 =AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'							,     trust_remote_code=lowerCAmelCase      )
        self.assertEqual(config.__class__.__name__							,     'NewModelConfig'      )

        # Test config can be reloaded.
        with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(lowerCAmelCase      )
              _lowercase			 =AutoConfig.from_pretrained(lowerCAmelCase							,     trust_remote_code=lowerCAmelCase      )
        self.assertEqual(reloaded_config.__class__.__name__							,     'NewModelConfig'      )




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






        class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
          _a		    =						"""new-model"""

        try:
              AutoConfig.register('new-model'							,     lowerCAmelCase      )
              # If remote code is not set, the default is to use local
              _lowercase			 =AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'      )
              self.assertEqual(config.__class__.__name__							,     'NewModelConfigLocal'      )

              # If remote code is disabled, we load the local one.
              _lowercase			 =AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'							,     trust_remote_code=lowerCAmelCase      )
              self.assertEqual(config.__class__.__name__							,     'NewModelConfigLocal'      )

              # If remote is enabled, we load from the Hub
              _lowercase			 =AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'							,     trust_remote_code=lowerCAmelCase      )
              self.assertEqual(config.__class__.__name__							,     'NewModelConfig'      )

        finally:
              if "new-model" in CONFIG_MAPPING._extra_content:
                    del CONFIG_MAPPING._extra_content["new-model"]





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_torch_available,
    is_vision_available,
)


lowercase_             =     {'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_             =     ['BeitFeatureExtractor']
  lowercase_             =     ['BeitImageProcessor']

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_             =     [
      'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST',
      'BeitForImageClassification',
      'BeitForMaskedImageModeling',
      'BeitForSemanticSegmentation',
      'BeitModel',
      'BeitPreTrainedModel',
  ]


try:
  if not is_flax_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_             =     [
      'FlaxBeitForImageClassification',
      'FlaxBeitForMaskedImageModeling',
      'FlaxBeitModel',
      'FlaxBeitPreTrainedModel',
  ]

if TYPE_CHECKING:
  from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .feature_extraction_beit import BeitFeatureExtractor
    from .image_processing_beit import BeitImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_beit import (
        BEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
        BeitForImageClassification,
        BeitForMaskedImageModeling,
        BeitForSemanticSegmentation,
        BeitModel,
        BeitPreTrainedModel,
    )

  try:
    if not is_flax_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_flax_beit import (
        FlaxBeitForImageClassification,
        FlaxBeitForMaskedImageModeling,
        FlaxBeitModel,
        FlaxBeitPreTrainedModel,
    )


else:
  import sys

  lowercase_             =     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


