

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  :      str			 ="""hf-internal-testing/tiny-random-bert"""
_lowerCAmelCase  :      int			 =os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
_lowerCAmelCase  :      Any			 ="""9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""

class __UpperCamelCase     (				unittest.TestCase		):






					'''simple docstring'''



					def    _UpperCAmelCase    (				self						):
						UpperCAmelCase__:	Optional[int]									= 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:
							UpperCAmelCase__:	Optional[int]									= 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.
						UpperCAmelCase__:	Union[str, Any]									= cached_file(lowerCamelCase__				,      lowerCamelCase__						)
						self.assertEqual(lowerCamelCase__				,      lowerCamelCase__						)

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





					def    _UpperCAmelCase    (				self						):
						with self.assertRaisesRegex(lowerCamelCase__				,      "is not a valid model identifier"						):
							UpperCAmelCase__:	Union[str, Any]									= cached_file("tiny-random-bert"				,      lowerCamelCase__						)

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

						with self.assertRaisesRegex(lowerCamelCase__				,      "does not appear to have a file named"						):
							UpperCAmelCase__:	List[str]									= cached_file(lowerCamelCase__				,      "conf"						)





					def    _UpperCAmelCase    (				self						):
						with self.assertRaisesRegex(lowerCamelCase__				,      "does not appear to have a file named"						):
							UpperCAmelCase__:	int									= cached_file(lowerCamelCase__				,      "conf"						)

						with open(os.path.join(lowerCamelCase__				,      "refs"				,      "main"						)						) as f:
							UpperCAmelCase__:	Dict									= f.read()
						self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase__				,      ".no_exist"				,      lowerCamelCase__				,      "conf"						)						)						)

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

						UpperCAmelCase__:	List[Any]									= cached_file(lowerCamelCase__				,      "conf"				,      local_files_only=lowerCamelCase__				,      _raise_exceptions_for_missing_entries=lowerCamelCase__						)
						self.assertIsNone(lowerCamelCase__						)

						UpperCAmelCase__:	Dict									= mock.Mock()
						UpperCAmelCase__:	str									= 5_0_0
						UpperCAmelCase__:	Union[str, Any]									= {}
						UpperCAmelCase__:	int									= HTTPError
						UpperCAmelCase__:	Dict									= {}

						# 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:
							UpperCAmelCase__:	Optional[int]									= 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    _UpperCAmelCase    (				self						):
						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    _UpperCAmelCase    (				self						):
						# `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"						)

						UpperCAmelCase__:	Optional[int]									= 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.
						UpperCAmelCase__:	Any									= json.loads(open(lowerCamelCase__				,      "r"						).read()						)
						self.assertEqual(config["hidden_size"]				,      7_6_8						)





					def    _UpperCAmelCase    (				self						):
						with tempfile.TemporaryDirectory() as tmp_dir:
							UpperCAmelCase__:	List[str]									= 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 inspect
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
_lowerCAmelCase  :      int			 ="""src/transformers"""


# This is to make sure the transformers module imported is the one in the repo.
_lowerCAmelCase  :      Dict			 =direct_transformers_import(PATH_TO_TRANSFORMERS)

_lowerCAmelCase  :      List[str]			 =transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
_lowerCAmelCase  :      int			 =re.compile(r"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""")


_lowerCAmelCase  :      Union[str, Any]			 ={
    """DecisionTransformerConfig""",
    """EncoderDecoderConfig""",
    """MusicgenConfig""",
    """RagConfig""",
    """SpeechEncoderDecoderConfig""",
    """TimmBackboneConfig""",
    """VisionEncoderDecoderConfig""",
    """VisionTextDualEncoderConfig""",
    """LlamaConfig""",
}



def 			_A	(      SCREAMING_SNAKE_CASE      ):
	UpperCAmelCase__:	str									= None

	# source code of `config_class`
	UpperCAmelCase__:	Optional[int]									= inspect.getsource(SCREAMING_SNAKE_CASE      )
	UpperCAmelCase__:	List[Any]									= _re_checkpoint.findall(SCREAMING_SNAKE_CASE      )

	# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
	# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
	for ckpt_name, ckpt_link in checkpoints:
		# allow the link to end with `/`
		if ckpt_link.endswith("/"      ):
			UpperCAmelCase__:	Any									= ckpt_link[:-1]

		# verify the checkpoint name corresponds to the checkpoint link
		UpperCAmelCase__:	int									= f"https://huggingface.co/{ckpt_name}"
		if ckpt_link == ckpt_link_from_name:
			UpperCAmelCase__:	Optional[int]									= ckpt_name
			break

	return checkpoint



def 			_A	(      ):
	UpperCAmelCase__:	List[str]									= []

	for config_class in list(CONFIG_MAPPING.values()      ):
		# Skip deprecated models
		if "models.deprecated" in config_class.__module__:
			continue
		UpperCAmelCase__:	Optional[Any]									= get_checkpoint_from_config_class(SCREAMING_SNAKE_CASE      )

		UpperCAmelCase__:	List[str]									= config_class.__name__
		if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
			configs_without_checkpoint.append(SCREAMING_SNAKE_CASE      )

	if len(SCREAMING_SNAKE_CASE      ) > 0:
		UpperCAmelCase__:	Dict									= "\n".join(sorted(SCREAMING_SNAKE_CASE      )      )
		raise ValueError(f"The following configurations don't contain any valid checkpoint:\n{message}"      )


if __name__ == "__main__":
					check_config_docstrings_have_checkpoints()