





from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar

UpperCAmelCase_					:   str 							=						TypeVar("""KEY""")
UpperCAmelCase_					:   int 							=						TypeVar("""VAL""")





@dataclass(frozen=__A     ,					slots=__A  )
class      lowercase__    (							Generic[KEY, VAL]  ):
  __UpperCamelCase	     =  42
  __UpperCamelCase	     =  42





class      lowercase__    (							_Item  ):







  def __init__(	self						):
       super().__init__(_lowercase    ,						_lowercase						)







  def __bool__(	self						):
       return False





UpperCAmelCase_					:   Optional[int] 							=						_DeletedItem()





class      lowercase__    (							MutableMapping[KEY, VAL]  ):







  def __init__(	self    ,						_lowercase = 8    ,						_lowercase = 0.75						):
       lowerCAmelCase_					:       Any    =		initial_block_size
       lowerCAmelCase_					:       list[_Item | None]    =		[None] * initial_block_size
       assert 0.0 < capacity_factor < 1.0
       lowerCAmelCase_					:       Tuple    =		capacity_factor
       lowerCAmelCase_					:       Optional[int]    =		0







  def 	UpperCAmelCase__		(	self    ,						_lowercase						):
       return hash(_lowercase						) % len(self._buckets						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase						):
       return (ind + 1) % len(self._buckets						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       Any    =		self._buckets[ind]
       if not stored:
            lowerCAmelCase_					:       List[str]    =		_Item(_lowercase    ,						_lowercase						)
            self._len += 1
            return True
       elif stored.key == key:
            lowerCAmelCase_					:       Any    =		_Item(_lowercase    ,						_lowercase						)
            return True
       else:
            return False







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Any    =		len(self._buckets						) * self._capacity_factor
       return len(self						) >= int(_lowercase						)







  def 	UpperCAmelCase__		(	self						):
       if len(self._buckets						) <= self._initial_block_size:
            return False
       lowerCAmelCase_					:       List[str]    =		len(self._buckets						) * self._capacity_factor / 2
       return len(self						) < limit







  def 	UpperCAmelCase__		(	self    ,						_lowercase						):
       lowerCAmelCase_					:       List[str]    =		self._buckets
       lowerCAmelCase_					:       str    =		[None] * new_size
       lowerCAmelCase_					:       Tuple    =		0
       for item in old_buckets:
            if item:
                 self._add_item(item.key    ,						item.val						)







  def 	UpperCAmelCase__		(	self						):
       self._resize(len(self._buckets						) * 2						)







  def 	UpperCAmelCase__		(	self						):
       self._resize(len(self._buckets						) // 2						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase						):
       lowerCAmelCase_					:       List[str]    =		self._get_bucket_index(_lowercase						)
       for _ in range(len(self._buckets						)						):
            yield ind
            lowerCAmelCase_					:       Optional[int]    =		self._get_next_ind(_lowercase						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase						):
       for ind in self._iterate_buckets(_lowercase						):
            if self._try_set(_lowercase    ,						_lowercase    ,						_lowercase						):
                 break







  def __setitem__(	self    ,						_lowercase    ,						_lowercase						):
       if self._is_full():
            self._size_up()

       self._add_item(_lowercase    ,						_lowercase						)







  def __delitem__(	self    ,						_lowercase						):
       for ind in self._iterate_buckets(_lowercase						):
            lowerCAmelCase_					:       str    =		self._buckets[ind]
            if item is None:
                 raise KeyError(_lowercase						)
            if item is _deleted:
                 continue
            if item.key == key:
                 lowerCAmelCase_					:       int    =		_deleted
                 self._len -= 1
                 break
       if self._is_sparse():
            self._size_down()







  def __getitem__(	self    ,						_lowercase						):
       for ind in self._iterate_buckets(_lowercase						):
            lowerCAmelCase_					:       Optional[int]    =		self._buckets[ind]
            if item is None:
                 break
            if item is _deleted:
                 continue
            if item.key == key:
                 return item.val
       raise KeyError(_lowercase						)







  def __len__(	self						):
       return self._len







  def __iter__(	self						):
       yield from (item.key for item in self._buckets if item)







  def __repr__(	self						):
       lowerCAmelCase_					:       str    =		""" ,""".join(
           F'{item.key}: {item.val}' for item in self._buckets if item						)
       return F'HashMap({val_string})'







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