


'''simple docstring'''


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







class 							__magic_name__	(       unittest.TestCase ):

     """simple docstring"""






     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       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:
               __A	:       List[Any]      =							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.
          __A	:       Optional[int]      =							cached_file(lowerCamelCase			,     lowerCamelCase		)
          self.assertEqual(lowerCamelCase			,     lowerCamelCase		)

          # Using a specific revision to test the full commit hash.
          __A	:       List[Any]      =							cached_file(lowerCamelCase			,     lowerCamelCase			,     revision="9b8c223"		)
          self.assertEqual(lowerCamelCase			,     os.path.join(lowerCamelCase			,     "snapshots"			,     lowerCamelCase			,     lowerCamelCase		)		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





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

          with self.assertRaisesRegex(lowerCamelCase			,     "is not a valid git identifier"		):
               __A	:       Union[str, Any]      =							cached_file(lowerCamelCase			,     lowerCamelCase			,     revision="aaaa"		)

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


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





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

          with open(os.path.join(lowerCamelCase			,     "refs"			,     "main"		)		) as f:
               __A	:       Optional[Any]      =							f.read()
          self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase			,     ".no_exist"			,     lowerCamelCase			,     "conf"		)		)		)

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

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

          __A	:       Dict      =							mock.Mock()
          __A	:       Dict      =							500
          __A	:       Optional[int]      =							{}
          __A	:       Union[str, Any]      =							HTTPError
          __A	:       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:
               __A	:       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 lowerCAmelCase__  (   self		):


          '''simple docstring'''





          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 lowerCAmelCase__  (   self		):


          '''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(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"		)

          __A	:       str      =							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.
          __A	:       str      =							json.loads(open(lowerCamelCase			,     "r"		).read()		)
          self.assertEqual(config["hidden_size"]			,     768		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          with tempfile.TemporaryDirectory() as tmp_dir:
               __A	:       int      =							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"		)		)





'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_UpperCamelCase 							=  {
    """configuration_upernet""": ["""UperNetConfig"""],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _UpperCamelCase 							=  [
          """UperNetForSemanticSegmentation""",
          """UperNetPreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_upernet import UperNetConfig

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel


else:
      import sys

      _UpperCamelCase 							=  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

