





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





class lowerCamelCase						(unittest.TestCase					):







  def 				UpperCAmelCase_				(		self		)		->						Dict:






        """simple docstring"""





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

        # File is cached at the same place the second time.
        _snake_case		:	Optional[int]					     =     cached_file(lowercase__     ,     lowercase__		)
        self.assertEqual(lowercase__     ,     lowercase__		)

        # Using a specific revision to test the full commit hash.
        _snake_case		:	List[str]					     =     cached_file(lowercase__     ,     lowercase__     ,     revision='''9b8c223'''		)
        self.assertEqual(lowercase__     ,     os.path.join(lowercase__     ,     '''snapshots'''     ,     lowercase__     ,     lowercase__		)		)







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






        """simple docstring"""





        with self.assertRaisesRegex(lowercase__     ,     '''is not a valid model identifier'''		):
              _snake_case		:	Any					     =     cached_file('''tiny-random-bert'''     ,     lowercase__		)

        with self.assertRaisesRegex(lowercase__     ,     '''is not a valid git identifier'''		):
              _snake_case		:	Tuple					     =     cached_file(lowercase__     ,     lowercase__     ,     revision='''aaaa'''		)

        with self.assertRaisesRegex(lowercase__     ,     '''does not appear to have a file named'''		):
              _snake_case		:	Tuple					     =     cached_file(lowercase__     ,     '''conf'''		)







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






        """simple docstring"""





        with self.assertRaisesRegex(lowercase__     ,     '''does not appear to have a file named'''		):
              _snake_case		:	List[Any]					     =     cached_file(lowercase__     ,     '''conf'''		)

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

        _snake_case		:	Any					     =     cached_file(lowercase__     ,     '''conf'''     ,     _raise_exceptions_for_missing_entries=lowercase__		)
        self.assertIsNone(lowercase__		)

        _snake_case		:	Union[str, Any]					     =     cached_file(lowercase__     ,     '''conf'''     ,     local_files_only=lowercase__     ,     _raise_exceptions_for_missing_entries=lowercase__		)
        self.assertIsNone(lowercase__		)

        _snake_case		:	List[Any]					     =     mock.Mock()
        _snake_case		:	Union[str, Any]					     =     500
        _snake_case		:	Any					     =     {}
        _snake_case		:	Dict					     =     HTTPError
        _snake_case		:	Tuple					     =     {}

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







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






        """simple docstring"""





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







  def 				UpperCAmelCase_				(		self		)		->						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(lowercase__     ,     '''is not a valid model identifier'''		):
              get_file_from_repo('''bert-base-case'''     ,     lowercase__		)

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

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







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






        """simple docstring"""





        with tempfile.TemporaryDirectory() as tmp_dir:
              _snake_case		:	Dict					     =     Path(lowercase__		) / '''a.txt'''
              filename.touch()
              self.assertEqual(get_file_from_repo(lowercase__     ,     '''a.txt'''		)     ,     str(lowercase__		)		)

              self.assertIsNone(get_file_from_repo(lowercase__     ,     '''b.txt'''		)		)









'''simple docstring'''

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCAmelCase					:		int		=							{
    'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'],
}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   UpperCAmelCase					:		Union[str, Any]		=							[
       'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST',
       'PegasusXForConditionalGeneration',
       'PegasusXModel',
       'PegasusXPreTrainedModel',
   ]


if TYPE_CHECKING:
   from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_pegasus_x import (
          PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST,
          PegasusXForConditionalGeneration,
          PegasusXModel,
          PegasusXPreTrainedModel,
      )


else:
   import sys

   UpperCAmelCase					:		Dict		=							_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


