





import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


__A									=				"hf-internal-testing/tiny-random-bert"
__A									=				os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert")
__A									=				"9b8c223d42b2188cb49d29af482996f9d0f3e5a6"



class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str])       ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:      Any			  =cached_file(UpperCAmelCase_       , UpperCAmelCase_)
   # Should have downloaded the file in here
   self.assertTrue(os.path.isdir(UpperCAmelCase_))
   # Cache should contain at least those three subfolders:
   for subfolder in ["blobs", "refs", "snapshots"]:
     self.assertTrue(os.path.isdir(os.path.join(UpperCAmelCase_       , UpperCAmelCase_)))
   with open(os.path.join(UpperCAmelCase_       , "refs"       , "main")) as f:
     lowerCamelCase__:      List[Any]			  =f.read()
   self.assertEqual(UpperCAmelCase_       , os.path.join(UpperCAmelCase_       , "snapshots"       , UpperCAmelCase_       , UpperCAmelCase_))
   self.assertTrue(os.path.isfile(UpperCAmelCase_))

   # File is cached at the same place the second time.
   lowerCamelCase__:      Optional[Any]			  =cached_file(UpperCAmelCase_       , UpperCAmelCase_)
   self.assertEqual(UpperCAmelCase_       , UpperCAmelCase_)

   # Using a specific revision to test the full commit hash.
   lowerCamelCase__:      str			  =cached_file(UpperCAmelCase_       , UpperCAmelCase_       , revision="9b8c223")
   self.assertEqual(UpperCAmelCase_       , os.path.join(UpperCAmelCase_       , "snapshots"       , UpperCAmelCase_       , UpperCAmelCase_))

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



   '''simple docstring'''



   with self.assertRaisesRegex(UpperCAmelCase_       , "is not a valid model identifier"):
     lowerCamelCase__:      List[Any]			  =cached_file("tiny-random-bert"       , UpperCAmelCase_)

   with self.assertRaisesRegex(UpperCAmelCase_       , "is not a valid git identifier"):
     lowerCamelCase__:      List[str]			  =cached_file(UpperCAmelCase_       , UpperCAmelCase_       , revision="aaaa")

   with self.assertRaisesRegex(UpperCAmelCase_       , "does not appear to have a file named"):
     lowerCamelCase__:      Optional[Any]			  =cached_file(UpperCAmelCase_       , "conf")

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->List[str]:



   '''simple docstring'''



   with self.assertRaisesRegex(UpperCAmelCase_       , "does not appear to have a file named"):
     lowerCamelCase__:      Dict			  =cached_file(UpperCAmelCase_       , "conf")

   with open(os.path.join(UpperCAmelCase_       , "refs"       , "main")) as f:
     lowerCamelCase__:      List[str]			  =f.read()
   self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase_       , ".no_exist"       , UpperCAmelCase_       , "conf")))

   lowerCamelCase__:      Union[str, Any]			  =cached_file(UpperCAmelCase_       , "conf"       , _raise_exceptions_for_missing_entries=UpperCAmelCase_)
   self.assertIsNone(UpperCAmelCase_)

   lowerCamelCase__:      Union[str, Any]			  =cached_file(UpperCAmelCase_       , "conf"       , local_files_only=UpperCAmelCase_       , _raise_exceptions_for_missing_entries=UpperCAmelCase_)
   self.assertIsNone(UpperCAmelCase_)

   lowerCamelCase__:      List[Any]			  =mock.Mock()
   lowerCamelCase__:      int			  =500
   lowerCamelCase__:      Union[str, Any]			  ={}
   lowerCamelCase__:      Any			  =HTTPError
   lowerCamelCase__:      List[Any]			  ={}

   # Under the mock environment we get a 500 error when trying to reach the tokenizer.
   with mock.patch("requests.Session.request"       , return_value=UpperCAmelCase_) as mock_head:
     lowerCamelCase__:      int			  =cached_file(UpperCAmelCase_       , "conf"       , _raise_exceptions_for_connection_errors=UpperCAmelCase_)
     self.assertIsNone(UpperCAmelCase_)
     # This check we did call the fake head request
     mock_head.assert_called()

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->Tuple:



   '''simple docstring'''



   self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only"       , UpperCAmelCase_))
   self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"       , UpperCAmelCase_))
   self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"       , UpperCAmelCase_))

 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict)       ->List[str]:



   '''simple docstring'''



   self.assertIsNone(get_file_from_repo("bert-base-cased"       , "ahah.txt"))

   # The function raises if the repository does not exist.
   with self.assertRaisesRegex(UpperCAmelCase_       , "is not a valid model identifier"):
     get_file_from_repo("bert-base-case"       , UpperCAmelCase_)

   # The function raises if the revision does not exist.
   with self.assertRaisesRegex(UpperCAmelCase_       , "is not a valid git identifier"):
     get_file_from_repo("bert-base-cased"       , UpperCAmelCase_       , revision="ahaha")

   lowerCamelCase__:      List[str]			  =get_file_from_repo("bert-base-cased"       , UpperCAmelCase_)
   # The name is the cached name which is not very easy to test, so instead we load the content.
   lowerCamelCase__:      List[str]			  =json.loads(open(UpperCAmelCase_       , "r").read())
   self.assertEqual(config["hidden_size"]       , 768)







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



   '''simple docstring'''



   with tempfile.TemporaryDirectory() as tmp_dir:
     lowerCamelCase__:      List[Any]			  =Path(UpperCAmelCase_) / "a.txt"
     filename.touch()
     self.assertEqual(get_file_from_repo(UpperCAmelCase_       , "a.txt")       , str(UpperCAmelCase_))

     self.assertIsNone(get_file_from_repo(UpperCAmelCase_       , "b.txt"))









"""simple docstring"""



import copy
import json
import os
import tempfile

from transformers import is_torch_available

from .test_configuration_utils import config_common_kwargs

class        a     (   a_	):







    def __init__(			self							,		_lowerCamelCase							,		_lowerCamelCase=None							,		_lowerCamelCase=True							,		_lowerCamelCase=None							,		**_lowerCamelCase       ):
      lowercase							    =       parent
      lowercase							    =       config_class
      lowercase							    =       has_text_modality
      lowercase							    =       kwargs
      lowercase							    =       common_properties







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )
      lowercase							    =       (
          ['hidden_size', 'num_attention_heads', 'num_hidden_layers']
          if self.common_properties is None
          else self.common_properties
      )

      # Add common fields for text models
      if self.has_text_modality:
        common_properties.extend(['vocab_size']       )

      # Test that config has the common properties as getters
      for prop in common_properties:
        self.parent.assertTrue(hasattr(_lowerCamelCase							,		_lowerCamelCase       )							,		msg=F'`{prop}` does not exist'       )

      # Test that config has the common properties as setter
      for idx, name in enumerate(_lowerCamelCase       ):
        try:
          setattr(_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase       )
          self.parent.assertEqual(
              getattr(_lowerCamelCase							,		_lowerCamelCase       )							,		_lowerCamelCase							,		msg=F'`{name} value {idx} expected, but was {getattr(_lowerCamelCase							,		_lowerCamelCase       )}'       )
        except NotImplementedError:
          # Some models might not be able to implement setters for common_properties
          # In that case, a NotImplementedError is raised
          pass

        # Test if config class can be called with Config(prop_name=..)
      for idx, name in enumerate(_lowerCamelCase       ):
        try:
          lowercase							    =       self.config_class(**{name: idx}       )
          self.parent.assertEqual(
              getattr(_lowerCamelCase							,		_lowerCamelCase       )							,		_lowerCamelCase							,		msg=F'`{name} value {idx} expected, but was {getattr(_lowerCamelCase							,		_lowerCamelCase       )}'       )
        except NotImplementedError:
          # Some models might not be able to implement setters for common_properties
          # In that case, a NotImplementedError is raised
          pass







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )
      lowercase							    =       json.loads(config.to_json_string()       )
      for key, value in self.inputs_dict.items():
        self.parent.assertEqual(obj[key]							,		_lowerCamelCase       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )

      with tempfile.TemporaryDirectory() as tmpdirname:
        lowercase							    =       os.path.join(_lowerCamelCase							,		'config.json'       )
        config_first.to_json_file(_lowerCamelCase       )
        lowercase							    =       self.config_class.from_json_file(_lowerCamelCase       )

      self.parent.assertEqual(config_second.to_dict()							,		config_first.to_dict()       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )

      with tempfile.TemporaryDirectory() as tmpdirname:
        config_first.save_pretrained(_lowerCamelCase       )
        lowercase							    =       self.config_class.from_pretrained(_lowerCamelCase       )

      self.parent.assertEqual(config_second.to_dict()							,		config_first.to_dict()       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )

      lowercase							    =       'test'
      with tempfile.TemporaryDirectory() as tmpdirname:
        lowercase							    =       os.path.join(_lowerCamelCase							,		_lowerCamelCase       )
        config_first.save_pretrained(_lowerCamelCase       )
        lowercase							    =       self.config_class.from_pretrained(_lowerCamelCase							,		subfolder=_lowerCamelCase       )

      self.parent.assertEqual(config_second.to_dict()							,		config_first.to_dict()       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict							,		num_labels=5       )
      self.parent.assertEqual(len(config.idalabel       )							,		5       )
      self.parent.assertEqual(len(config.labelaid       )							,		5       )

      lowercase							    =       3
      self.parent.assertEqual(len(config.idalabel       )							,		3       )
      self.parent.assertEqual(len(config.labelaid       )							,		3       )







    def 			UpperCamelCase_      (			self       ):
      if self.config_class.is_composition:
        return
      lowercase							    =       self.config_class()
      self.parent.assertIsNotNone(_lowerCamelCase       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       copy.deepcopy(_lowerCamelCase       )
      lowercase							    =       self.config_class(**_lowerCamelCase       )
      lowercase							    =       []
      for key, value in config_common_kwargs.items():
        if key == "torch_dtype":
          if not is_torch_available():
            continue
          else:
            import torch

            if config.torch_dtype != torch.floataa:
              wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa)       )
        elif getattr(_lowerCamelCase							,		_lowerCamelCase       ) != value:
          wrong_values.append((key, getattr(_lowerCamelCase							,		_lowerCamelCase       ), value)       )

      if len(_lowerCamelCase       ) > 0:
        lowercase							    =       '\n'.join([F'- {v[0]}: got {v[1]} instead of {v[2]}' for v in wrong_values]       )
        raise ValueError(F'The following keys were not properly set in the config:\n{errors}'       )







    def 			UpperCamelCase_      (			self       ):
      self.create_and_test_config_common_properties()
      self.create_and_test_config_to_json_string()
      self.create_and_test_config_to_json_file()
      self.create_and_test_config_from_and_save_pretrained()
      self.create_and_test_config_from_and_save_pretrained_subfolder()
      self.create_and_test_config_with_num_labels()
      self.check_config_can_be_init_without_params()
      self.check_config_arguments_init()


