





import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
      import torch

      UpperCAmelCase_					:   Any 							=						True
except ImportError:
      UpperCAmelCase_					:   Union[str, Any] 							=						False


try:
      from torch.hub import _get_torch_home

      UpperCAmelCase_					:   Optional[Any] 							=						_get_torch_home()
except ImportError:
      UpperCAmelCase_					:   Any 							=						os.path.expanduser(
          os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch"""))
      )

UpperCAmelCase_					:   Optional[int] 							=						os.path.join(torch_cache_home, """transformers""")

UpperCAmelCase_					:   List[Any] 							=						"""https://cdn.huggingface.co"""
UpperCAmelCase_					:   Tuple 							=						"""https://s3.amazonaws.com/models.huggingface.co/bert"""
UpperCAmelCase_					:   List[str] 							=						"""/""".join(str(Path(__file__).resolve()).split("""/""")[:-1])
UpperCAmelCase_					:   Any 							=						os.path.join(PATH, """config.yaml""")
UpperCAmelCase_					:   Optional[int] 							=						os.path.join(PATH, """attributes.txt""")
UpperCAmelCase_					:   List[str] 							=						os.path.join(PATH, """objects.txt""")
UpperCAmelCase_					:   str 							=						os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path)
UpperCAmelCase_					:   str 							=						os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE)
UpperCAmelCase_					:   str 							=						os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE)
UpperCAmelCase_					:   Optional[int] 							=						"""pytorch_model.bin"""
UpperCAmelCase_					:   List[Any] 							=						"""config.yaml"""






def 							_lowerCAmelCase (  _a   :					Optional[int]=OBJECTS					,   _a   :					Union[str, Any]=ATTRIBUTES			)	->			Tuple:
     lowerCAmelCase_					:       Tuple    =		[]
     with open(_a			) as f:
          for object in f.readlines():
               vg_classes.append(object.split(""","""			)[0].lower().strip()			)

     lowerCAmelCase_					:       List[Any]    =		[]
     with open(_a			) as f:
          for object in f.readlines():
               vg_attrs.append(object.split(""","""			)[0].lower().strip()			)
     return vg_classes, vg_attrs






def 							_lowerCAmelCase (  _a   :					Union[str, Any]			)	->			Any:
     lowerCAmelCase_					:       Optional[Any]    =		OrderedDict()
     with open(_a					,   """rb"""			) as f:
          lowerCAmelCase_					:       Union[str, Any]    =		pkl.load(_a			)["""model"""]
     for k in copy.deepcopy(list(ckp.keys()			)			):
          lowerCAmelCase_					:       Union[str, Any]    =		ckp.pop(_a			)
          if isinstance(_a					,   np.ndarray			):
               lowerCAmelCase_					:       Optional[int]    =		torch.tensor(_a			)
          else:
               assert isinstance(_a					,   torch.tensor			), type(_a			)
          lowerCAmelCase_					:       int    =		v
     return r





class      lowercase__    :
  __UpperCamelCase	     =  {}







  def __init__(	self    ,						_lowercase    ,						_lowercase = "root"    ,						_lowercase=0						):
       lowerCAmelCase_					:       List[Any]    =		name
       lowerCAmelCase_					:       Optional[Any]    =		level
       lowerCAmelCase_					:       Optional[int]    =		{}
       for k, v in dictionary.items():
            if v is None:
                 raise ValueError()
            lowerCAmelCase_					:       Optional[int]    =		copy.deepcopy(_lowercase						)
            lowerCAmelCase_					:       Tuple    =		copy.deepcopy(_lowercase						)
            if isinstance(_lowercase    ,						_lowercase						):
                 lowerCAmelCase_					:       List[str]    =		Config(_lowercase    ,						name=_lowercase    ,						level=level + 1						)
            lowerCAmelCase_					:       Any    =		v
            setattr(self    ,						_lowercase    ,						_lowercase						)

       lowerCAmelCase_					:       int    =		d







  def __repr__(	self						):
       return str(list((self._pointer.keys())						)						)







  def __setattr__(	self    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       str    =		val
       lowerCAmelCase_					:       Optional[int]    =		val
       lowerCAmelCase_					:       Union[str, Any]    =		key.split("""."""						)
       lowerCAmelCase_					:       Tuple    =		len(_lowercase						) - 1
       lowerCAmelCase_					:       List[Any]    =		self._pointer
       if len(_lowercase						) > 1:
            for i, l in enumerate(_lowercase						):
                 if hasattr(self    ,						_lowercase						) and isinstance(getattr(self    ,						_lowercase						)    ,						_lowercase						):
                      setattr(getattr(self    ,						_lowercase						)    ,						""".""".join(levels[i:]						)    ,						_lowercase						)
                 if l == last_level:
                      lowerCAmelCase_					:       List[Any]    =		val
                 else:
                      lowerCAmelCase_					:       str    =		pointer[l]







  def 	UpperCAmelCase__		(	self						):
       return self._pointer







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase						):
       with open(F'{file_name}'    ,						"""w"""						) as stream:
            dump(_lowercase    ,						_lowercase						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase						):
       with open(F'{file_name}'    ,						"""w"""						) as stream:
            json.dump(_lowercase    ,						_lowercase						)







  @staticmethod
  def 	UpperCAmelCase__		(	_lowercase						):
       with open(_lowercase						) as stream:
            lowerCAmelCase_					:       Dict    =		load(_lowercase    ,						Loader=_lowercase						)
       return data







  def __str__(	self						):
       lowerCAmelCase_					:       Optional[int]    =		"""    """
       if self._name != "root":
            lowerCAmelCase_					:       List[Any]    =		F'{t * (self._level-1)}{self._name}:\n'
       else:
            lowerCAmelCase_					:       str    =		""""""
       lowerCAmelCase_					:       Union[str, Any]    =		self._level
       for i, (k, v) in enumerate(self._pointer.items()						):
            if isinstance(_lowercase    ,						_lowercase						):
                 r += F'{t * (self._level)}{v}\n'
                 self._level += 1
            else:
                 r += F'{t * (self._level)}{k}: {v} ({type(_lowercase						).__name__})\n'
            lowerCAmelCase_					:       Any    =		level
       return r[:-1]







  @classmethod
  def 	UpperCAmelCase__		(	cls    ,						_lowercase    ,						**_lowercase						):
       lowerCAmelCase_					:       Union[str, Any]    =		cls.get_config_dict(_lowercase    ,						**_lowercase						)
       return cls(_lowercase						)







  @classmethod
  def 	UpperCAmelCase__		(	cls    ,						_lowercase    ,						**_lowercase						):
       lowerCAmelCase_					:       Tuple    =		kwargs.pop("""cache_dir"""    ,						_lowercase						)
       lowerCAmelCase_					:       Dict    =		kwargs.pop("""force_download"""    ,						_lowercase						)
       lowerCAmelCase_					:       Union[str, Any]    =		kwargs.pop("""resume_download"""    ,						_lowercase						)
       lowerCAmelCase_					:       Dict    =		kwargs.pop("""proxies"""    ,						_lowercase						)
       lowerCAmelCase_					:       str    =		kwargs.pop("""local_files_only"""    ,						_lowercase						)

       if os.path.isdir(_lowercase						):
            lowerCAmelCase_					:       List[Any]    =		os.path.join(_lowercase    ,						_lowercase						)
       elif os.path.isfile(_lowercase						) or is_remote_url(_lowercase						):
            lowerCAmelCase_					:       Optional[Any]    =		pretrained_model_name_or_path
       else:
            lowerCAmelCase_					:       Optional[int]    =		hf_bucket_url(_lowercase    ,						filename=_lowercase    ,						use_cdn=_lowercase						)

       try:
            # Load from URL or cache if already cached
            lowerCAmelCase_					:       List[str]    =		cached_path(
                _lowercase    ,						cache_dir=_lowercase    ,						force_download=_lowercase    ,						proxies=_lowercase    ,						resume_download=_lowercase    ,						local_files_only=_lowercase    ,						)
            # Load config dict
            if resolved_config_file is None:
                 raise EnvironmentError

            lowerCAmelCase_					:       Tuple    =		Config.load_yaml(_lowercase						)

       except EnvironmentError:
            lowerCAmelCase_					:       List[str]    =		"""Can't load config for"""
            raise EnvironmentError(_lowercase						)

       if resolved_config_file == config_file:
            print("""loading configuration file from path"""						)
       else:
            print("""loading configuration file cache"""						)

       return Config.load_yaml(_lowercase						), kwargs






def 							_lowerCAmelCase (  _a   :					Any			)	->			int:
     lowerCAmelCase_					:       Any    =		torch.load("""dump.pt"""					,   map_location=in_tensor.device			)
     lowerCAmelCase_					:       Optional[Any]    =		in_tensor.numpy()
     lowerCAmelCase_					:       Union[str, Any]    =		out_tensor.numpy()[0]
     print(na.shape					,   na[0, 0, :5]			)
     print(na.shape					,   na[0, 0, :5]			)
     assert np.allclose(_a					,   _a					,   rtol=0.01					,   atol=0.1			), (
         F'{sum([1 for x in np.isclose(_a					,   _a					,   rtol=0.01					,   atol=0.1			).flatten() if x is False]			)/len(na.flatten()			)*1_00:.4f} %'
         " element-wise mismatch"
     )
     raise Exception("""tensors are all good"""			)

     # Hugging face functions below






def 							_lowerCAmelCase (  _a   :					Any			)	->			Optional[Any]:
     lowerCAmelCase_					:       List[Any]    =		urlparse(_a			)
     return parsed.scheme in ("http", "https")






def 							_lowerCAmelCase (  _a   :					str					,   _a   :					str					,   _a   :					Optional[Any]=True			)	->			str:
     lowerCAmelCase_					:       int    =		CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
     lowerCAmelCase_					:       List[str]    =		"""/""" not in model_id
     if legacy_format:
          return F'{endpoint}/{model_id}-{filename}'
     else:
          return F'{endpoint}/{model_id}/{filename}'






def 							_lowerCAmelCase (  _a   :					List[Any]					,   _a   :					Any					,   _a   :					List[Any]=None					,   _a   :					Dict=0					,   _a   :					Dict=None					,   )	->			List[str]:
     lowerCAmelCase_					:       List[Any]    =		"""python/{}""".format(sys.version.split()[0]			)
     if _torch_available:
          ua += "; torch/{}".format(torch.__version__			)
     if isinstance(_a					,   _a			):
          ua += "; " + "; ".join("""{}/{}""".format(_a					,   _a			) for k, v in user_agent.items()			)
     elif isinstance(_a					,   _a			):
          ua += "; " + user_agent
     lowerCAmelCase_					:       Optional[int]    =		{"""user-agent""": ua}
     if resume_size > 0:
          lowerCAmelCase_					:       Any    =		"""bytes=%d-""" % (resume_size,)
     lowerCAmelCase_					:       Optional[int]    =		requests.get(_a					,   stream=_a					,   proxies=_a					,   headers=_a			)
     if response.status_code == 4_16:  # Range not satisfiable
          return
     lowerCAmelCase_					:       Optional[int]    =		response.headers.get("""Content-Length"""			)
     lowerCAmelCase_					:       Dict    =		resume_size + int(_a			) if content_length is not None else None
     lowerCAmelCase_					:       Dict    =		tqdm(
         unit="""B"""					,   unit_scale=_a					,   total=_a					,   initial=_a					,   desc="""Downloading"""					,   )
     for chunk in response.iter_content(chunk_size=10_24			):
          if chunk:  # filter out keep-alive new chunks
               progress.update(len(_a			)			)
               temp_file.write(_a			)
     progress.close()






def 							_lowerCAmelCase (  _a   :					Tuple					,   _a   :					Tuple=None					,   _a   :					List[Any]=False					,   _a   :					str=None					,   _a   :					List[Any]=10					,   _a   :					str=False					,   _a   :					Dict=None					,   _a   :					Optional[int]=False					,   )	->			int:
     if cache_dir is None:
          lowerCAmelCase_					:       Any    =		TRANSFORMERS_CACHE
     if isinstance(_a					,   _a			):
          lowerCAmelCase_					:       Optional[int]    =		str(_a			)

     os.makedirs(_a					,   exist_ok=_a			)

     lowerCAmelCase_					:       int    =		None
     if not local_files_only:
          try:
               lowerCAmelCase_					:       List[str]    =		requests.head(_a					,   allow_redirects=_a					,   proxies=_a					,   timeout=_a			)
               if response.status_code == 2_00:
                    lowerCAmelCase_					:       int    =		response.headers.get("""ETag"""			)
          except (EnvironmentError, requests.exceptions.Timeout):
               # etag is already None
               pass

     lowerCAmelCase_					:       List[Any]    =		url_to_filename(_a					,   _a			)

     # get cache path to put the file
     lowerCAmelCase_					:       Union[str, Any]    =		os.path.join(_a					,   _a			)

     # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
     # try to get the last downloaded one
     if etag is None:
          if os.path.exists(_a			):
               return cache_path
          else:
               lowerCAmelCase_					:       Tuple    =		[
                   file
                   for file in fnmatch.filter(os.listdir(_a			)					,   filename + """.*"""			)
                   if not file.endswith(""".json"""			) and not file.endswith(""".lock"""			)
               ]
               if len(_a			) > 0:
                    return os.path.join(_a					,   matching_files[-1]			)
               else:
                    # If files cannot be found and local_files_only=True,
                    # the models might've been found if local_files_only=False
                    # Notify the user about that
                    if local_files_only:
                         raise ValueError(
                             """Cannot find the requested files in the cached path and outgoing traffic has been"""
                             """ disabled. To enable model look-ups and downloads online, set 'local_files_only'"""
                             """ to False."""			)
                    return None

    # From now on, etag is not None.
     if os.path.exists(_a			) and not force_download:
          return cache_path

     # Prevent parallel downloads of the same file with a lock.
     lowerCAmelCase_					:       Optional[int]    =		cache_path + """.lock"""
     with FileLock(_a			):
          # If the download just completed while the lock was activated.
          if os.path.exists(_a			) and not force_download:
               # Even if returning early like here, the lock will be released.
               return cache_path

          if resume_download:
               lowerCAmelCase_					:       Any    =		cache_path + """.incomplete"""

               @contextmanager
               def _resumable_file_manager():
                    with open(_a					,   """a+b"""			) as f:
                         yield f

               lowerCAmelCase_					:       str    =		_resumable_file_manager
               if os.path.exists(_a			):
                    lowerCAmelCase_					:       Dict    =		os.stat(_a			).st_size
               else:
                    lowerCAmelCase_					:       Any    =		0
          else:
               lowerCAmelCase_					:       List[str]    =		partial(tempfile.NamedTemporaryFile					,   dir=_a					,   delete=_a			)
               lowerCAmelCase_					:       List[Any]    =		0

          # Download to temporary file, then copy to cache dir once finished.
          # Otherwise you get corrupt cache entries if the download gets interrupted.
          with temp_file_manager() as temp_file:
               print(
                   """%s not found in cache or force_download set to True, downloading to %s"""					,   _a					,   temp_file.name					,   )

               http_get(
                   _a					,   _a					,   proxies=_a					,   resume_size=_a					,   user_agent=_a					,   )

          os.replace(temp_file.name					,   _a			)

          lowerCAmelCase_					:       Tuple    =		{"""url""": url, """etag""": etag}
          lowerCAmelCase_					:       List[Any]    =		cache_path + """.json"""
          with open(_a					,   """w"""			) as meta_file:
               json.dump(_a					,   _a			)

     return cache_path






def 							_lowerCAmelCase (  _a   :					str					,   _a   :					int=None			)	->			List[Any]:
     lowerCAmelCase_					:       int    =		url.encode("""utf-8"""			)
     lowerCAmelCase_					:       Optional[Any]    =		shaaaa(_a			)
     lowerCAmelCase_					:       List[str]    =		url_hash.hexdigest()

     if etag:
          lowerCAmelCase_					:       Any    =		etag.encode("""utf-8"""			)
          lowerCAmelCase_					:       List[Any]    =		shaaaa(_a			)
          filename += "." + etag_hash.hexdigest()

     if url.endswith(""".h5"""			):
          filename += ".h5"

     return filename






def 							_lowerCAmelCase (  _a   :					List[str]					,   _a   :					Any=None					,   _a   :					List[str]=False					,   _a   :					Optional[int]=None					,   _a   :					Any=False					,   _a   :					str=None					,   _a   :					Optional[int]=False					,   _a   :					Dict=False					,   _a   :					List[str]=False					,   )	->			Optional[Any]:
     if cache_dir is None:
          lowerCAmelCase_					:       Union[str, Any]    =		TRANSFORMERS_CACHE
     if isinstance(_a					,   _a			):
          lowerCAmelCase_					:       Optional[Any]    =		str(_a			)
     if isinstance(_a					,   _a			):
          lowerCAmelCase_					:       List[Any]    =		str(_a			)

     if is_remote_url(_a			):
          # URL, so get it from the cache (downloading if necessary)
          lowerCAmelCase_					:       Optional[int]    =		get_from_cache(
              _a					,   cache_dir=_a					,   force_download=_a					,   proxies=_a					,   resume_download=_a					,   user_agent=_a					,   local_files_only=_a					,   )
     elif os.path.exists(_a			):
          # File, and it exists.
          lowerCAmelCase_					:       Union[str, Any]    =		url_or_filename
     elif urlparse(_a			).scheme == "":
          # File, but it doesn't exist.
          raise EnvironmentError("""file {} not found""".format(_a			)			)
     else:
          # Something unknown
          raise ValueError("""unable to parse {} as a URL or as a local path""".format(_a			)			)

     if extract_compressed_file:
          if not is_zipfile(_a			) and not tarfile.is_tarfile(_a			):
               return output_path

          # Path where we extract compressed archives
          # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
          lowerCAmelCase_					:       Optional[Any]    =		os.path.split(_a			)
          lowerCAmelCase_					:       Any    =		output_file.replace("""."""					,   """-"""			) + """-extracted"""
          lowerCAmelCase_					:       str    =		os.path.join(_a					,   _a			)

          if os.path.isdir(_a			) and os.listdir(_a			) and not force_extract:
               return output_path_extracted

          # Prevent parallel extractions
          lowerCAmelCase_					:       Dict    =		output_path + """.lock"""
          with FileLock(_a			):
               shutil.rmtree(_a					,   ignore_errors=_a			)
               os.makedirs(_a			)
               if is_zipfile(_a			):
                    with ZipFile(_a					,   """r"""			) as zip_file:
                         zip_file.extractall(_a			)
                         zip_file.close()
               elif tarfile.is_tarfile(_a			):
                    lowerCAmelCase_					:       List[Any]    =		tarfile.open(_a			)
                    tar_file.extractall(_a			)
                    tar_file.close()
               else:
                    raise EnvironmentError("""Archive format of {} could not be identified""".format(_a			)			)

          return output_path_extracted

     return output_path






def 							_lowerCAmelCase (  _a   :					int					,   _a   :					List[str]=","			)	->			Tuple:
     assert isinstance(_a					,   _a			)
     if os.path.isfile(_a			):
          with open(_a			) as f:
               lowerCAmelCase_					:       List[Any]    =		eval(f.read()			)
     else:
          lowerCAmelCase_					:       List[Any]    =		requests.get(_a			)
          try:
               lowerCAmelCase_					:       List[str]    =		requests.json()
          except Exception:
               lowerCAmelCase_					:       Optional[Any]    =		req.content.decode()
               assert data is not None, "could not connect"
               try:
                    lowerCAmelCase_					:       Tuple    =		eval(_a			)
               except Exception:
                    lowerCAmelCase_					:       Tuple    =		data.split("""\n"""			)
          req.close()
     return data






def 							_lowerCAmelCase (  _a   :					Tuple			)	->			Optional[Any]:
     lowerCAmelCase_					:       int    =		requests.get(_a			)
     lowerCAmelCase_					:       int    =		np.array(Image.open(BytesIO(response.content			)			)			)
     return img






def 							_lowerCAmelCase (  _a   :					Dict			)	->			Union[str, Any]:
     lowerCAmelCase_					:       str    =		url.split("""/"""			)[-1]
     if fn not in os.listdir(os.getcwd()			):
          wget.download(_a			)
     with open(_a					,   """rb"""			) as stream:
          lowerCAmelCase_					:       Tuple    =		pkl.load(_a			)
     lowerCAmelCase_					:       int    =		weights.pop("""model"""			)
     lowerCAmelCase_					:       List[Any]    =		{}
     for k, v in model.items():
          lowerCAmelCase_					:       Optional[int]    =		torch.from_numpy(_a			)
          if "running_var" in k:
               lowerCAmelCase_					:       Union[str, Any]    =		torch.tensor([0]			)
               lowerCAmelCase_					:       List[Any]    =		k.replace("""running_var"""					,   """num_batches_tracked"""			)
               lowerCAmelCase_					:       List[Any]    =		zero
     return new






def 							_lowerCAmelCase (  )	->			Tuple:
     print(F'{os.path.abspath(os.path.join(_a					,   os.pardir			)			)}/demo.ipynb'			)






def 							_lowerCAmelCase (  _a   :					Optional[Any]					,   _a   :					Optional[int]="RGB"			)	->			Optional[Any]:
     assert isinstance(_a					,   _a			)
     if os.path.isfile(_a			):
          lowerCAmelCase_					:       Optional[int]    =		cva.imread(_a			)
     else:
          lowerCAmelCase_					:       List[Any]    =		get_image_from_url(_a			)
          assert img is not None, F'could not connect to: {im}'
     lowerCAmelCase_					:       Dict    =		cva.cvtColor(_a					,   cva.COLOR_BGR2RGB			)
     if input_format == "RGB":
          lowerCAmelCase_					:       Optional[int]    =		img[:, :, ::-1]
     return img







def 							_lowerCAmelCase (  _a   :					Union[str, Any]					,   _a   :					Union[str, Any]=1			)	->			Optional[int]:
     return (images[i : i + batch] for i in range(0					,   len(_a			)					,   _a			))







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_					:   List[str] 							=						"""hf-internal-testing/tiny-random-bert"""
UpperCAmelCase_					:   List[Any] 							=						os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
UpperCAmelCase_					:   Tuple 							=						"""9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""





class      lowercase__    (							unittest.TestCase  ):







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Union[str, Any]    =		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:
            lowerCAmelCase_					:       Any    =		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.
       lowerCAmelCase_					:       Dict    =		cached_file(_lowercase    ,						_lowercase						)
       self.assertEqual(_lowercase    ,						_lowercase						)

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







  def 	UpperCAmelCase__		(	self						):
       with self.assertRaisesRegex(_lowercase    ,						"""is not a valid model identifier"""						):
            lowerCAmelCase_					:       Dict    =		cached_file("""tiny-random-bert"""    ,						_lowercase						)

       with self.assertRaisesRegex(_lowercase    ,						"""is not a valid git identifier"""						):
            lowerCAmelCase_					:       Tuple    =		cached_file(_lowercase    ,						_lowercase    ,						revision="""aaaa"""						)

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







  def 	UpperCAmelCase__		(	self						):
       with self.assertRaisesRegex(_lowercase    ,						"""does not appear to have a file named"""						):
            lowerCAmelCase_					:       Any    =		cached_file(_lowercase    ,						"""conf"""						)

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

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

       lowerCAmelCase_					:       Any    =		cached_file(_lowercase    ,						"""conf"""    ,						local_files_only=_lowercase    ,						_raise_exceptions_for_missing_entries=_lowercase						)
       self.assertIsNone(_lowercase						)

       lowerCAmelCase_					:       Any    =		mock.Mock()
       lowerCAmelCase_					:       Optional[Any]    =		500
       lowerCAmelCase_					:       Any    =		{}
       lowerCAmelCase_					:       List[str]    =		HTTPError
       lowerCAmelCase_					:       List[str]    =		{}

       # 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:
            lowerCAmelCase_					:       Union[str, Any]    =		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						):
       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						):
       # `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(_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"""						)

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







  def 	UpperCAmelCase__		(	self						):
       with tempfile.TemporaryDirectory() as tmp_dir:
            lowerCAmelCase_					:       Optional[Any]    =		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"""						)						)
