


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


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







class        __lowercase       (							unittest.TestCase  ):



		"""simple docstring"""

		def 					__A   ( self	)  -> List[str]:







					'''simple docstring'''







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

					# File is cached at the same place the second time.
					lowerCamelCase    		=  cached_file(A		,      A	)
					self.assertEqual(A		,      A	)

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







		def 					__A   ( self	)  -> Dict:







					'''simple docstring'''







					with self.assertRaisesRegex(A		,      """is not a valid model identifier"""	):
								lowerCamelCase    		=  cached_file("""tiny-random-bert"""		,      A	)

					with self.assertRaisesRegex(A		,      """is not a valid git identifier"""	):
								lowerCamelCase    		=  cached_file(A		,      A		,      revision="""aaaa"""	)

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







		def 					__A   ( self	)  -> Optional[Any]:







					'''simple docstring'''







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

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

					lowerCamelCase    		=  cached_file(A		,      """conf"""		,      _raise_exceptions_for_missing_entries=A	)
					self.assertIsNone(A	)

					lowerCamelCase    		=  cached_file(A		,      """conf"""		,      local_files_only=A		,      _raise_exceptions_for_missing_entries=A	)
					self.assertIsNone(A	)

					lowerCamelCase    		=  mock.Mock()
					lowerCamelCase    		=  5_00
					lowerCamelCase    		=  {}
					lowerCamelCase    		=  HTTPError
					lowerCamelCase    		=  {}

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







		def 					__A   ( self	)  -> List[Any]:







					'''simple docstring'''







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







		def 					__A   ( self	)  -> Tuple:







					'''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(A		,      """is not a valid model identifier"""	):
								get_file_from_repo("""bert-base-case"""		,      A	)

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

					lowerCamelCase    		=  get_file_from_repo("""bert-base-cased"""		,      A	)
					# The name is the cached name which is not very easy to test, so instead we load the content.
					lowerCamelCase    		=  json.loads(open(A		,      """r"""	).read()	)
					self.assertEqual(config["""hidden_size"""]		,      7_68	)







		def 					__A   ( self	)  -> Any:







					'''simple docstring'''







					with tempfile.TemporaryDirectory() as tmp_dir:
								lowerCamelCase    		=  Path(A	) / """a.txt"""
								filename.touch()
								self.assertEqual(get_file_from_repo(A		,      """a.txt"""	)		,      str(A	)	)

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





# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from .config import config_command_parser
from .config_args import default_config_file, load_config_from_file  # noqa: F401
from .default import default_command_parser
from .update import update_command_parser






def 	__lowerCamelCase						(							lowerCamelCase__		:						Any=None      ):





			'''simple docstring'''




			lowerCamelCase    		=  argparse.ArgumentParser(add_help=lowerCamelCase__  ,							allow_abbrev=lowerCamelCase__      )
			# The main config parser
			lowerCamelCase    		=  config_command_parser(lowerCamelCase__      )
			# The subparser to add commands to
			lowerCamelCase    		=  config_parser.add_subparsers(title="""subcommands"""  ,							dest="""subcommand"""      )

			# Then add other parsers with the parent parser
			default_command_parser(lowerCamelCase__  ,							parents=[parent_parser]      )
			update_command_parser(lowerCamelCase__  ,							parents=[parent_parser]      )

			return config_parser






def 	__lowerCamelCase						(							):





			'''simple docstring'''




			lowerCamelCase    		=  get_config_parser()
			lowerCamelCase    		=  config_parser.parse_args()

			if not hasattr(lowerCamelCase__  ,							"""func"""      ):
						config_parser.print_help()
						exit(1      )

			# Run
			args.func(lowerCamelCase__      )


if __name__ == "__main__":
		main()

