

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,
)


lowerCAmelCase							:  List[str]            =						"""hf-internal-testing/tiny-random-bert"""
lowerCAmelCase							:  str            =						os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
lowerCAmelCase							:  Dict            =						"""9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""



class   __lowercase    (			unittest.TestCase     ):




			"""simple docstring"""







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

									# File is cached at the same place the second time.
									SCREAMING_SNAKE_CASE_:			str  		=	cached_file(lowerCAmelCase__       ,						lowerCAmelCase__)
									self.assertEqual(lowerCAmelCase__       ,						lowerCAmelCase__)

									# Using a specific revision to test the full commit hash.
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	cached_file(lowerCAmelCase__       ,						lowerCAmelCase__       ,						revision="9b8c223")
									self.assertEqual(lowerCAmelCase__       ,						os.path.join(lowerCAmelCase__       ,						"snapshots"       ,						lowerCAmelCase__       ,						lowerCAmelCase__))



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									with self.assertRaisesRegex(lowerCAmelCase__       ,						"is not a valid model identifier"):
															SCREAMING_SNAKE_CASE_:			int  		=	cached_file("tiny-random-bert"       ,						lowerCAmelCase__)

									with self.assertRaisesRegex(lowerCAmelCase__       ,						"is not a valid git identifier"):
															SCREAMING_SNAKE_CASE_:			List[Any]  		=	cached_file(lowerCAmelCase__       ,						lowerCAmelCase__       ,						revision="aaaa")

									with self.assertRaisesRegex(lowerCAmelCase__       ,						"does not appear to have a file named"):
															SCREAMING_SNAKE_CASE_:			List[Any]  		=	cached_file(lowerCAmelCase__       ,						"conf")



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									with self.assertRaisesRegex(lowerCAmelCase__       ,						"does not appear to have a file named"):
															SCREAMING_SNAKE_CASE_:			Any  		=	cached_file(lowerCAmelCase__       ,						"conf")

									with open(os.path.join(lowerCAmelCase__       ,						"refs"       ,						"main")) as f:
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	f.read()
									self.assertTrue(os.path.isfile(os.path.join(lowerCAmelCase__       ,						".no_exist"       ,						lowerCAmelCase__       ,						"conf")))

									SCREAMING_SNAKE_CASE_:			List[str]  		=	cached_file(lowerCAmelCase__       ,						"conf"       ,						_raise_exceptions_for_missing_entries=lowerCAmelCase__)
									self.assertIsNone(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[str]  		=	cached_file(lowerCAmelCase__       ,						"conf"       ,						local_files_only=lowerCAmelCase__       ,						_raise_exceptions_for_missing_entries=lowerCAmelCase__)
									self.assertIsNone(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[Any]  		=	mock.Mock()
									SCREAMING_SNAKE_CASE_:			Dict  		=	500
									SCREAMING_SNAKE_CASE_:			Tuple  		=	{}
									SCREAMING_SNAKE_CASE_:			str  		=	HTTPError
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	{}

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



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only"       ,						lowerCAmelCase__))
									self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"       ,						lowerCAmelCase__))
									self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"       ,						lowerCAmelCase__))



			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									# `get_file_from_repo` returns None if the file does not exist
									self.assertIsNone(get_file_from_repo("bert-base-cased"       ,						"ahah.txt"))

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

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

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




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Dict):
									with tempfile.TemporaryDirectory() as tmp_dir:
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	Path(lowerCAmelCase__) / "a.txt"
															filename.touch()
															self.assertEqual(get_file_from_repo(lowerCAmelCase__       ,						"a.txt")       ,						str(lowerCAmelCase__))

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









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


lowerCAmelCase							:  Union[str, Any]            =						get_tests_dir("""fixtures/dummy-config.json""")



class   __lowercase    (			unittest.TestCase     ):




			"""simple docstring"""







			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									SCREAMING_SNAKE_CASE_:			Dict  		=	0



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any):
									self.assertIsNotNone(transformers.models.auto.__spec__)
									self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"))



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	AutoConfig.from_pretrained("bert-base-uncased")
									self.assertIsInstance(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	AutoConfig.from_pretrained(lowerCAmelCase__)
									self.assertIsInstance(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									SCREAMING_SNAKE_CASE_:			Tuple  		=	AutoConfig.from_pretrained(lowerCAmelCase__)
									self.assertIsInstance(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	AutoConfig.for_model("roberta")
									self.assertIsInstance(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									with tempfile.TemporaryDirectory() as tmp_dir:
															# This model name contains bert and roberta, but roberta ends up being picked.
															SCREAMING_SNAKE_CASE_:			int  		=	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({}))
															SCREAMING_SNAKE_CASE_:			Any  		=	AutoConfig.from_pretrained(lowerCAmelCase__)
															self.assertEqual(type(lowerCAmelCase__)       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]):
									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
															SCREAMING_SNAKE_CASE_:			List[Any]  		=	CustomConfig()
															with tempfile.TemporaryDirectory() as tmp_dir:
																					config.save_pretrained(lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	AutoConfig.from_pretrained(lowerCAmelCase__)
																					self.assertIsInstance(lowerCAmelCase__       ,						lowerCAmelCase__)

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



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[str]):
									with self.assertRaisesRegex(
									    lowerCAmelCase__       ,						"bert-base is not a local folder and is not a valid model identifier"):
															SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoConfig.from_pretrained("bert-base")



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									with self.assertRaisesRegex(
									    lowerCAmelCase__       ,						R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"):
															SCREAMING_SNAKE_CASE_:			str  		=	AutoConfig.from_pretrained(lowerCAmelCase__       ,						revision="aaaaaa")



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]):
									with self.assertRaisesRegex(
									    lowerCAmelCase__       ,						"hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."       ,						):
															SCREAMING_SNAKE_CASE_:			int  		=	AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo")



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[str]):
									# If remote code is not set, we will time out when asking whether to load the model.
									with self.assertRaises(lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_:			str  		=	AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model")
									# If remote code is disabled, we can't load this config.
									with self.assertRaises(lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"       ,						trust_remote_code=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			str  		=	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__)
															SCREAMING_SNAKE_CASE_:			Any  		=	AutoConfig.from_pretrained(lowerCAmelCase__       ,						trust_remote_code=lowerCAmelCase__)
									self.assertEqual(reloaded_config.__class__.__name__       ,						"NewModelConfig")




			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):



									class   __lowercase    (			UpperCAmelCase_     ):




												"""simple docstring"""







												_UpperCAmelCase       :							int      							=					'''new-model'''

									try:
															AutoConfig.register("new-model"       ,						lowerCAmelCase__)
															# If remote code is not set, the default is to use local
															SCREAMING_SNAKE_CASE_:			int  		=	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.
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	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
															SCREAMING_SNAKE_CASE_:			int  		=	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"]






